Can org.json.JSONObject produce {“und”:[{“value”:“[email protected]”}]}?

Refresh

April 2019

Views

139 time

1

I am trying to use org.json.JSONObject to build the following target json string:

{"und":[{"value":"[email protected]"}]} 

Here is my code:

JSONObject und = new JSONObject();
und.accumulate("und", new JSONObject().put("value", "[email protected]"));   
System.out.println( und.toString() );

But it produces the following:

{"und":{"value":"[email protected]"}} 

How can I produce the target json string?

Thanks and regards.

EDIT

Thanks to SLaks's input, here is the code that produces the target string:

     JSONObject und = new JSONObject();
     JSONArray arr = new JSONArray();
     und.put("und", arr);
     arr.put(new JSONObject().put("value", "[email protected]"));
     System.out.println( und.toString() );

1 answers

1

You might want to take a look at Jackson, it's one of the most efficient and supported JSON libraries available on Java.

If you are familiar with unmarshalling/deserialization, you can turn an POJO into json and vise versa.

@JsonSerialize(include = JsonSerialize.Inclusion.NON_DEFAULT)
public class SomeBean {
    Und[] und;
    // TODO: Getters and setters

    public static Und class {
        public String value;
        // TODO: Getters and setters 
    }
}

If you are directly parsing a JSON string or file, you can use the ObjectMapper class

SomeBean someBean = new ObjectMapper().readValue("input goes here", SomeBean.class);

// If you want just a string you can pass in the String class
String json = new ObjectMapper().readValue("input", String.class);

If the JSON is coming from a web service, check out Spring's restTemplate, super easy to work with.

RestTemplate restTemplate = new RestTemplate();
SomeBean someBean = restTemplate.getForEntity("URI goes here", SomeBean.class);

String json = restTemplate.getForEntity("URI goes here", String.class);
Dan