How to serialize Object to JSON?

前端 未结 7 1668
面向向阳花
面向向阳花 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:08

    The "reference" Java implementation by Sean Leary is here on github. Make sure to have the latest version - different libraries pull in versions buggy old versions from 2009.

    Java EE 7 has a JSON API in javax.json, see the Javadoc. From what I can tell, it doesn't have a simple method to marshall any object to JSON, you need to construct a JsonObject or a JsonArray.

    import javax.json.*;
    
    JsonObject value = Json.createObjectBuilder()
     .add("firstName", "John")
     .add("lastName", "Smith")
     .add("age", 25)
     .add("address", Json.createObjectBuilder()
         .add("streetAddress", "21 2nd Street")
         .add("city", "New York")
         .add("state", "NY")
         .add("postalCode", "10021"))
     .add("phoneNumber", Json.createArrayBuilder()
         .add(Json.createObjectBuilder()
             .add("type", "home")
             .add("number", "212 555-1234"))
         .add(Json.createObjectBuilder()
             .add("type", "fax")
             .add("number", "646 555-4567")))
     .build();
    
    JsonWriter jsonWriter = Json.createWriter(...);
    jsonWriter.writeObject(value);
    jsonWriter.close();
    

    But I assume the other libraries like GSON will have adapters to create objects implementing those interfaces.

提交回复
热议问题