Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create a complex json object in java?

Tags:

I'm trying to create this json object in java and struggling:

{     "notification": {         "message": "test",         "sound": "sounds/alarmsound.wav",         "target": {             "apps": [                 {                     "id": "app_id",                     "platforms": [                         "ios"                     ]                 }             ]         }     },     "access_token": "access_token" } 

Any assistance in how someone would create that in java would be appreciated!

like image 367
pixelworlds Avatar asked Jan 08 '13 04:01

pixelworlds


People also ask

What is complex JSON?

Complex JSON objects are those objects that contain a nested object inside the other. Example of Complex JSON Object.

What is JSON object class in Java?

JsonObject class represents an immutable JSON object value (an unordered collection of zero or more name/value pairs). It also provides unmodifiable map view to the JSON object name/value mappings. A JsonObject instance can be created from an input source using JsonReader.


1 Answers

If you really are looking into creating JSON objects, Jackson has all you want:

final JsonNodeFactory factory = JsonNodeFactory.instance;  final ObjectNode node = factory.objectNode();  final ObjectNode child = factory.objectNode(); // the child  child.put("message", "test");  // etc etc  // and then:  node.set("notification", child); // node.put(String, ObjectNode) has been deprecated 

The resulting node is an ObjectNode, which inherits JsonNode, which means you get all of JsonNode's niceties:

  • a sensible .toString() representation;
  • navigation capabilities (.get(), .path() -- GSON has no equivalent for that, in particular not .path(), since it cannot model a node that is missing);
  • MissingNode to represent a node that isn't there, and NullNode to represent JSON null, all of which inherit JsonNode (GSON has no equivalent for that -- and all of JsonNode's navigation methods are also available on such nodes);
  • and of course .equals()/.hashCode().
like image 113
fge Avatar answered Sep 28 '22 14:09

fge