How to serialize Object to JSON?

前端 未结 7 1696
面向向阳花
面向向阳花 2020-11-27 05:49

I need to serialize some objects to a JSON and send to a WebService. How can I do it using the org.json library? Or I\'ll have to use another one? Here is the class I need t

7条回答
  •  囚心锁ツ
    2020-11-27 06:13

    After JAVAEE8 published , now you can use the new JAVAEE API JSON-B (JSR367)

    Maven dependency :

    
        javax.json.bind
        javax.json.bind-api
        1.0
    
    
    
        org.eclipse
        yasson
        1.0
    
    
    
        org.glassfish
        javax.json
        1.1
    
    

    Here is some code snapshot :

    Jsonb jsonb = JsonbBuilder.create();
    // Two important API : toJson fromJson
    String result = jsonb.toJson(listaDePontos);
    

    JSON-P is also updated to 1.1 and more easy to use. JSON-P 1.1 (JSR374)

    Maven dependency :

    
        javax.json
        javax.json-api
        1.1
    
    
    
        org.glassfish
        javax.json
        1.1
    
    

    Here is the runnable code snapshot :

    String data = "{\"name\":\"Json\","
                    + "\"age\": 29,"
                    + " \"phoneNumber\": [10000,12000],"
                    + "\"address\": \"test\"}";
            JsonObject original = Json.createReader(new StringReader(data)).readObject();
            /**getValue*/
            JsonPointer pAge = Json.createPointer("/age");
            JsonValue v = pAge.getValue(original);
            System.out.println("age is " + v.toString());
            JsonPointer pPhone = Json.createPointer("/phoneNumber/1");
            System.out.println("phoneNumber 2 is " + pPhone.getValue(original).toString());
    

提交回复
热议问题