23

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!

ROMANIA_engineer
  • 54,432
  • 29
  • 203
  • 199
pixelworlds
  • 818
  • 2
  • 11
  • 22
  • Short answer: use Jackson. GSON is good, but navigation wise, Jackson is miles ahead. – fge Jan 08 '13 at 04:23
  • I've tried using the Jackson Tree Model which looks something like this - ObjectMapper mapper = new ObjectMapper(); JsonNode rootNode = mapper.createObjectNode(); ((ObjectNode) rootNode).put("name", "Tatu"); - I haven't been able to figure out how to nest other objects and arrays however. – pixelworlds Jan 08 '13 at 04:30

6 Answers6

46

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().
fge
  • 119,121
  • 33
  • 254
  • 329
  • This is very helpful! I will try to implement this and see how it goes! Thank you again for your time and help! – pixelworlds Jan 08 '13 at 04:35
  • Glad it helped! Note that an `ObjectMapper` is not really meant for node creation, its main purpose is really serialization and deserialization. And internally, it uses a `JsonNodeFactory`. – fge Jan 08 '13 at 04:47
  • I'm typically a javascript/PHP developer - so this java project has been very frustrating for me! I really appreciate the kindness! – pixelworlds Jan 08 '13 at 04:51
  • Yeah, unlike JavaScript and PHP, Java has no native type for maps -- but unlike both of these languages, it can actually represent them in more powerful ways, and with type safety to boost! A different world... – fge Jan 08 '13 at 04:54
  • your solution worked perfectly! I posted my implementation for others! Thanks again fge! – pixelworlds Jan 08 '13 at 08:26
  • JsonNodeFactory doesn't have a publicly available constructor anymore. you need to use ObjectNode child = JsonNodeFactory.instance.objectNode(); // the child – comiventor Nov 08 '17 at 09:00
24

For those who try to use the answers of this thread, note that

JsonNodeFactory nodeFactory = new JsonNodeFactory();

Is not working anymore with the package jackson-databind. Instead you should do

final JsonNodeFactory nodeFactory = JsonNodeFactory.instance;

See this answer: https://stackoverflow.com/a/16974850/3824918

Community
  • 1
  • 1
Cithel
  • 686
  • 7
  • 21
10
JSONObject jsonComplex = new JSONObject();
    JSONObject notification = new JSONObject();
    notification.put("message", "test");
    notification.put("sound", "sounds_alarmsound.wav");
    JSONObject targetJsonObject= new JSONObject();
    JSONArray targetJsonArray= new JSONArray();
    JSONObject appsJsonObject= new JSONObject();
    appsJsonObject.put("id","app_id");
    JSONArray platformArray = new JSONArray();
    platformArray.add("ios");
    appsJsonObject.put("platforms",platformArray);
    targetJsonArray.add(appsJsonObject);
    targetJsonObject.put("apps", targetJsonArray);
    notification.put("target", targetJsonObject);
    jsonComplex.put("notification", notification);
    jsonComplex.put("access_token", "access_token");
    System.out.println(jsonComplex);
Soumya
  • 109
  • 1
  • 2
  • 12
    Next time it would be good to add some explanation, and not just dump code. – Cthulhu Dec 02 '13 at 18:24
  • 3
    IMHO when the code is clear, self-explanatory and ituitive, there is no need of verbose extra lines of text in name of explantion. Let the ans be short and simple. – Dexter Feb 09 '18 at 09:12
  • @Dexter Code won't be self intuitive to every one. – Rishi Dec 30 '19 at 04:31
  • 3
    You are right @Rishi, but at this instance, one coder asked a question related to code. Another coder answered with some code. Have you gone through above code- Its very simple and intuitive. So here I do not think extra explanation is expected. – Dexter Dec 31 '19 at 05:16
5

Thanks go to @fge who provided the necessary information for me to solve this.

Here's what I did to solve this problem!

JsonNodeFactory nodeFactory = new JsonNodeFactory();

        ObjectNode pushContent = nodeFactory.objectNode();
        ObjectNode notification = nodeFactory.objectNode();
        ObjectNode appsObj = nodeFactory.objectNode();
        ObjectNode target = nodeFactory.objectNode();

        ArrayNode apps = nodeFactory.arrayNode();
        ArrayNode platforms = nodeFactory.arrayNode();

        platforms.add("ios");

        appsObj.put("id","app_id");
        appsObj.put("platforms",platforms);

        apps.add(appsObj);

        notification.put("message",filledForm.field("text").value());
        notification.put("sound","sounds/alarmsound.wav");
        notification.put("target", target);

        target.put("apps",apps);

        pushContent.put("notification", notification);
        pushContent.put("access_token","access_token");

        if(!filledForm.field("usage").value().isEmpty()) {
            target.put("usage",filledForm.field("usage").value());
        }

        if(!filledForm.field("latitude").value().isEmpty() && !filledForm.field("longitude").value().isEmpty() && !filledForm.field("radius").value().isEmpty()) {
            target.put("latitude",filledForm.field("latitude").value());
            target.put("longitude",filledForm.field("longitude").value());
            target.put("radius",filledForm.field("radius").value());
        }

Printing pushContent than outputs the exact json object I needed to create!

Hope this helps someone else out there too!

Rich

pixelworlds
  • 818
  • 2
  • 11
  • 22
2

I'd rather create classes representing that object, and convert it into JSON. I presume you got that JSON interface elsewhere and is lot on how to create it from Java.

class ToJson{
    private Notification notification;
    private String access_token;
}

public class Notification{
    private String message;
    private String sound;
    private Target target;
}

public class Target{
    private Apps apps[];
}

public class Apps{
    private String id;
    private Plataform plataforms[];
}

public class Plataform{
    privte String ios;
}

Then you convert a filled ToJson object to JSON using any lib/framework you like.

Hikari
  • 3,797
  • 12
  • 47
  • 77
0

There are a variety of libraries that can help you here.

If you run into more specific problems with these libraries, you should post them.

Jeff Storey
  • 56,312
  • 72
  • 233
  • 406
  • As someone looking to get back into Java, I found this by accident: should I assume it isn't worth my time? (I haven't started working with JSON in Java, just considering it in the future.) – Ian Stapleton Cordasco Jan 08 '13 at 04:23
  • Jeff, thanks for your response. I had looked into Jackson already and tried to implement it. I'm not normally a java developer, however, and wasn't able to figure out the process. – pixelworlds Jan 08 '13 at 04:24
  • @sigmavirus24 I haven't used the crockford library. – Jeff Storey Jan 08 '13 at 04:24
  • @pixelworlds What did you have trouble with? "I wasn't able to figure out the process" doesn't help people help you. – Jeff Storey Jan 08 '13 at 04:25
  • @JeffStorey sorry for hijacking the thread from the original intended discussion, can you also update your answer regarding the Pros and Cons in using each of the libraries. I am a big fan of Jackson but wanted to know if there are any known short comings which is solved by other libraries. – Srinivas Jan 08 '13 at 04:27
  • 1
    @Srinivas A google search will help you there. Just search for jackson vs json or whatever you want to compare. – Jeff Storey Jan 08 '13 at 04:29
  • @JeffStorey - I was trying to implement the Jackson Tree Model example found here: [link](http://wiki.fasterxml.com/JacksonTreeModel) but I'm unsure how to start nesting other json objects and arrays inside the original root object. – pixelworlds Jan 08 '13 at 04:33