24

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!

2
  • Short answer: use Jackson. GSON is good, but navigation wise, Jackson is miles ahead. Commented Jan 8, 2013 at 4: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. Commented Jan 8, 2013 at 4:30

6 Answers 6

47

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().
Sign up to request clarification or add additional context in comments.

6 Comments

This is very helpful! I will try to implement this and see how it goes! Thank you again for your time and help!
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.
I'm typically a javascript/PHP developer - so this java project has been very frustrating for me! I really appreciate the kindness!
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...
your solution worked perfectly! I posted my implementation for others! Thanks again fge!
|
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

Comments

11
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);

4 Comments

Next time it would be good to add some explanation, and not just dump code.
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 Code won't be self intuitive to every one.
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.
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

Comments

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.

Comments

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.

7 Comments

As someone looking to get back into Java, I found this by accident: <github.com/douglascrockford/JSON-java> should I assume it isn't worth my time? (I haven't started working with JSON in Java, just considering it in the future.)
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.
@sigmavirus24 I haven't used the crockford library.
@pixelworlds What did you have trouble with? "I wasn't able to figure out the process" doesn't help people help you.
@Srinivas A google search will help you there. Just search for jackson vs json or whatever you want to compare.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.