Example usage for org.json.simple JSONObject put

List of usage examples for org.json.simple JSONObject put

Introduction

In this page you can find the example usage for org.json.simple JSONObject put.

Prototype

V put(K key, V value);

Source Link

Document

Associates the specified value with the specified key in this map (optional operation).

Usage

From source file:jsonencodedemo.JsonEncodeDemo.java

public static void main(String[] args) {
    JSONObject obj = new JSONObject();

    obj.put("name", "Jordan");
    obj.put("school", "BYUI");
    obj.put("age", new Integer(31));
    obj.put("year", new Integer(2015));
    obj.put("is_student", new Boolean(true));

    System.out.print(obj);/*from   w w w .j  a  v a  2s.c o  m*/
}

From source file:de.root1.kad.cvbackend.Test.java

public static void main(String[] args) {
    String ga = "";
    String value = "";

    JSONObject jsonResponse = new JSONObject();
    JSONObject jsonData = new JSONObject();
    jsonData.put(ga, value);
    jsonResponse.put("d", jsonData);
    jsonResponse.put("i", "1");
    System.out.println(jsonResponse.toJSONString());
}

From source file:json.WriteToFile.java

public static void main(String[] args) {
    JSONObject countryObj = new JSONObject();
    countryObj.put("Name", "Kenya");
    countryObj.put("Population", new Integer(430000000));
    JSONArray listOfCounties = new JSONArray();
    listOfCounties.add("Nairobi");
    listOfCounties.add("Kiambu");
    listOfCounties.add("Murang'a");

    countryObj.put("Counties", listOfCounties);
    try {//from w  w w . ja  v a  2  s .  c  o m
        //writing to file
        File file = new File("/home/mars/Desktop/JsonExample1.json");
        file.createNewFile();
        FileWriter fw = new FileWriter(file);
        System.out.println("Writing JSON object to file");
        System.out.println("---------------------------");
        System.out.println(countryObj);

        fw.write(countryObj + "");
        fw.flush();
        fw.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:jsonpractice.Jsonpractice.java

public static void main(String[] args) throws IOException {
    JSONObject countryObj = new JSONObject();
    countryObj.put("Name", "India");
    countryObj.put("Population", 1000000);

    JSONArray listOfStates = new JSONArray();
    listOfStates.add("Madhya Pradesh");
    listOfStates.add("Maharastra");
    listOfStates.add("Tamil Nadu");

    countryObj.put("States", listOfStates);

    try {/*from  www . j  a  v a 2 s  .  c  o m*/
        File file = new File("C:\\Users\\user\\Documents\\CountryJSONFile.json");
        file.createNewFile();
        try (FileWriter fileWriter = new FileWriter(file)) {
            System.out.println("Writing JSON OBJECT to file");
            System.out.println("-----------------------------");
            System.out.println(countryObj);

            fileWriter.write(countryObj.toJSONString());
            fileWriter.flush();
        } catch (IOException e) {
        }

    } catch (IOException e) {
    }
}

From source file:cat.tv3.eng.rec.recomana.lupa.visualization.TextsResumeToJson.java

public static void main(String[] args) throws IOException {
    String host = args[0];//from   w  ww  . ja va2 s .co m
    int port = Integer.parseInt(args[1]);
    Jedis jedis = new Jedis(host, port, 20000);

    String[] text_keys = jedis.keys("hash_id_*").toArray(new String[0]);

    for (int i = 0; i < text_keys.length; ++i) {
        JSONArray resume = new JSONArray();
        String[] split_resume_name = text_keys[i].split("_");
        String id = split_resume_name[split_resume_name.length - 1];

        JSONObject text = new JSONObject();
        text.put("id", id);
        text.put("tittle", jedis.hget(text_keys[i], "tittle"));
        text.put("text", jedis.hget(text_keys[i], "text"));

        resume.add(text);

        saveResults(resume, id);
    }
    jedis.disconnect();
}

From source file:cat.tv3.eng.rec.recomana.lupa.visualization.RecommendationToJson.java

public static void main(String[] args) throws IOException {
    final int TOTAL_WORDS = 20;
    String host = args[0];//from   www. j  a  v  a  2s  . c  o  m
    int port = Integer.parseInt(args[1]);
    Jedis jedis = new Jedis(host, port, 20000);

    String[] recommendation_keys = jedis.keys("recommendations_*").toArray(new String[0]);

    for (int i = 0; i < recommendation_keys.length; ++i) {
        JSONArray recommendations = new JSONArray();
        String[] split_reco_name = recommendation_keys[i].split("_");
        String id = split_reco_name[split_reco_name.length - 1];

        Set<Tuple> recos = jedis.zrangeWithScores(recommendation_keys[i], 0, -1);
        Iterator<Tuple> it = recos.iterator();

        while (it.hasNext()) {
            Tuple t = it.next();

            JSONObject new_reco = new JSONObject();
            new_reco.put("id", t.getElement());
            new_reco.put("distance", (double) Math.round(t.getScore() * 10000) / 10000);

            recommendations.add(new_reco);
        }
        saveResults(recommendations, id);
    }
    jedis.disconnect();
}

From source file:com.example.main.Main.java

/**
 * @param args//w  ww.  ja  v a2  s  . c o  m
 */
public static void main(String[] args) throws Exception {
    String webappDirLocation = "src/main/webapp/";

    // The port that we should run on can be set into an environment variable
    // Look for that variable and default to 8080 if it isn't there.
    String webPort = System.getenv("PORT");
    if (webPort == null || webPort.isEmpty()) {
        webPort = "8082";
    }

    Server server = new Server(Integer.valueOf(webPort));
    WebAppContext root = new WebAppContext();

    root.setContextPath("/");
    root.setDescriptor(webappDirLocation + "/WEB-INF/web.xml");
    root.setResourceBase(webappDirLocation);

    PersistenceManager.getInstance().getEntityManagerFactory();

    // Parent loader priority is a class loader setting that Jetty accepts.
    // By default Jetty will behave like most web containers in that it will
    // allow your application to replace non-server libraries that are part of the
    // container. Setting parent loader priority to true changes this behavior.
    // Read more here: http://wiki.eclipse.org/Jetty/Reference/Jetty_Classloading
    root.setParentLoaderPriority(true);

    try {
        JSONObject datos = new JSONObject();
        datos.put("nombrePagina", "Competencias");
        datos.put("urlPagina", "localHost:8082");
        JSONObject datos2 = new JSONObject();
        datos2.put("nombrePagina", "Competencias");
        datos2.put("nuevoEstado", "Activo");
        JSONObject datos3 = new JSONObject();
        datos3.put("nombrePagina", "Competencias");
        datos3.put("nombreServicio", "Competencias");
        datos3.put("rutaServicio", "Competencias");
        JSONObject datos4 = new JSONObject();
        datos4.put("nombrePagina", "Competencias");
        datos4.put("nombreServicio", "Ganadores");
        datos4.put("rutaServicio", "Competencias/winners/{name}");

        Client client = Client.create();
        WebResource target = client.resource(SERVIDOR_ZK + "inscribirPagina");
        target.post(JSONObject.class, datos);
        target = client.resource(SERVIDOR_ZK + "estadoPagina");
        target.post(JSONObject.class, datos2);
        target = client.resource(SERVIDOR_ZK + "servicioPagina");
        target.post(JSONObject.class, datos3);
        target = client.resource(SERVIDOR_ZK + "servicioPagina");
        target.post(JSONObject.class, datos4);

        client.destroy();

    } catch (Exception e) {
        e.printStackTrace();
    }

    server.setHandler(root);

    server.start();
    server.join();
}

From source file:com.francetelecom.admindm.changedustate.callviaacs.CallChangeDUStateUninstallCapabilityOnEdgeAcs.java

/**
 * @param args// w  w  w .  j  a v a  2  s . c  o  m
 */
public static void main(final String[] args) {
    HttpClient client = new HttpClient();
    // client.getHostConfiguration().setProxy("", );

    String host = null;
    String port = null;
    String address = "http://" + host + ":" + port + "/edge/api/";

    String acsUsername = null;
    String acsPassword = null;

    if (host == null || port == null || acsUsername == null || acsPassword == null) {
        throw new InvalidParameterException("Fill host: " + host + ", port: " + port + ", acsUsername: "
                + acsUsername + ", and acsPassword: " + acsPassword + ".");
    }

    String realm = "NBBS_API_Realm";

    AuthScope authscope = new AuthScope(host, Integer.parseInt(port), realm);

    // client.getState().setCredentials(realm, host,
    // new UsernamePasswordCredentials(acsUsername, acsPassword));

    client.getState().setCredentials(authscope, new UsernamePasswordCredentials(acsUsername, acsPassword));

    PostMethod post = null;

    // -----
    // ----- Execution de la capability : changeDUStateUninstall
    // -----

    post = new PostMethod(address + "capability/execute");

    post.addParameter(new NameValuePair("deviceId", "10003"));
    post.addParameter(new NameValuePair("timeoutMs", "60000"));
    post.addParameter(new NameValuePair("capability", "\"changeDUStateUninstall\""));

    // UUID: string
    // Version: string
    // ExecutionEnvRef: String

    JSONObject object = new JSONObject();
    object.put("UUID", "45");
    object.put("Version", "2.2.0");
    object.put("ExecutionEnvRef", "ExecutionEnvRef_value");
    post.addParameter(new NameValuePair("input", object.toString()));

    post.setDoAuthentication(true);

    // post.addParameter(new NameValuePair("deviceId", "60001"));

    // -----
    // ----- Partie commune : Execution du post
    // -----

    try {
        int status = client.executeMethod(post);
        System.out.println("status: " + status);
        String resp = post.getResponseBodyAsString();
        System.out.println("resp: " + resp);
    } catch (HttpException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        // release any connection resources used by the method
        post.releaseConnection();
    }
}

From source file:contractEditor.contractHOST4.java

public static void main(String[] args) {

    JSONObject obj = new JSONObject();
    obj.put("name", "HOST4");
    obj.put("context", "VM-deployment");

    //obj.put("Context", new Integer);

    HashMap serviceDescription = new HashMap();
    serviceDescription.put("location", "France");
    serviceDescription.put("certificate", "true");
    serviceDescription.put("volume", "100_GB");
    serviceDescription.put("price", "3_euro");

    obj.put("serviceDescription", serviceDescription);

    HashMap gauranteeTerm = new HashMap();
    gauranteeTerm.put("availability", "more_98_percentage");
    obj.put("gauranteeTerm", gauranteeTerm);

    //Constraint1

    ArrayList creationConstraint1 = new ArrayList();
    ArrayList totalConstraint = new ArrayList();
    totalConstraint.add(creationConstraint1);

    obj.put("creationConstraint", totalConstraint);

    try {/*  w  w w.ja va2 s . c  o  m*/

        FileWriter file = new FileWriter("confSP" + File.separator + "Host4.json");
        file.write(obj.toJSONString());
        file.flush();
        file.close();

    } catch (IOException e) {
        e.printStackTrace();
    }

    System.out.print(obj);

    /*
            
    JSONParser parser = new JSONParser();
            
    try {
            
    Object obj2 = parser.parse(new FileReader("confSP\\confHost1.json"));
            
    JSONObject jsonObject = (JSONObject) obj2;
            
        HashMap serviceDescription2=(HashMap) jsonObject.get("serviceDescription");
                 
        method.printHashMap(serviceDescription2);
                
                
        HashMap gauranteeTerm2=(HashMap) jsonObject.get("gauranteeTerm");
                 
        method.printHashMap(gauranteeTerm2);
                
                
                
        ArrayList creationConstraint=(ArrayList) jsonObject.get("creationConstraint");
                
        method.printArrayList(creationConstraint);
            
            
    } catch (FileNotFoundException e) {
    e.printStackTrace();
    } catch (IOException e) {
    e.printStackTrace();
    } catch (ParseException e) {
    e.printStackTrace();
    }
            
            
            
            
            
    */

}

From source file:com.francetelecom.admindm.changedustate.callviaacs.CallChangeDUStateUpdateCapabilityOnEdgeAcs.java

/**
 * @param args// w w  w  .  j ava  2  s .  co m
 */
public static void main(final String[] args) {
    HttpClient client = new HttpClient();
    // client.getHostConfiguration().setProxy("", );

    String host = null;
    String port = null;
    String address = "http://" + host + ":" + port + "/edge/api/";

    String acsUsername = null;
    String acsPassword = null;

    if (host == null || port == null || acsUsername == null || acsPassword == null) {
        throw new InvalidParameterException("Fill host: " + host + ", port: " + port + ", acsUsername: "
                + acsUsername + ", and acsPassword: " + acsPassword + ".");
    }

    String realm = "NBBS_API_Realm";

    AuthScope authscope = new AuthScope(host, Integer.parseInt(port), realm);

    // client.getState().setCredentials(realm, host,
    // new UsernamePasswordCredentials(acsUsername, acsPassword));

    client.getState().setCredentials(authscope, new UsernamePasswordCredentials(acsUsername, acsPassword));

    PostMethod post = null;

    // -----
    // ----- Execution de la capability : changeDUStateUpdate
    // -----

    post = new PostMethod(address + "capability/execute");

    post.addParameter(new NameValuePair("deviceId", "10003"));
    post.addParameter(new NameValuePair("timeoutMs", "60000"));
    post.addParameter(new NameValuePair("capability", "\"changeDUStateUpdate\""));

    // UUID: string
    // Version: string
    // URL: string
    // Username: string
    // Password: string

    JSONObject object = new JSONObject();
    object.put("UUID", "45");
    object.put("Version", "1.0.0");
    object.put("URL", "http://127.0.0.1:8085/a/org.apache.felix.http.jetty-2.2.0.jar");
    object.put("Username", "Username_value");
    object.put("Password", "Password_value");
    post.addParameter(new NameValuePair("input", object.toString()));

    post.setDoAuthentication(true);

    // post.addParameter(new NameValuePair("deviceId", "60001"));

    // -----
    // ----- Partie commune : Execution du post
    // -----

    try {
        int status = client.executeMethod(post);
        System.out.println("status: " + status);
        String resp = post.getResponseBodyAsString();
        System.out.println("resp: " + resp);
    } catch (HttpException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        // release any connection resources used by the method
        post.releaseConnection();
    }
}