How to get something iterable out of a JSON String? - java

I am trying to parse an Object which is in JSON format like
[{"id": "1", "revisionId":"2"}, {"id":"3", "revisionId":"4"}]
I want to extract the ids to be an iterable array like
["1", "3"]
I have tried using the JSONObject library but it seems when I do this:
JSONObject jsonObject = new JSONObject(obj);
it converts the object into a structure like
{"empty":false}
so using jsonObject.get("id") doesn't work.

Your json string is a json array, not an object, so you can't pass that to JSONObject, but you can use a JSONArray instead.
To get the list of object IDs, you can try something like:
List<String> ids = new JsonArray(obj).toList() // turn the JSONArray into a list
.stream()
.map(JSONObject.class::cast) // cast elements to JSONObjects
.map(json -> json.getString("id")) // extract the id from each object
.collect(Collectors.toList());

Hey you try to parse a json array:
'[{"id": "1", "revisionId":"2"}, {"id":"3", "revisionId":"4"}]'
into a JSONObject. Try something like that:
'{"array": [{"id": "1", "revisionId":"2"}, {"id":"3", "revisionId":"4"}]}'
Then you can access the array with new 'JSONObject(jsonString).getJSONArray("array");'
Let me know if it work for you :-)

Related

Read the outer-most JSON object but not the inner ones using Jackson?

This is similar to this question but it's a little different.
Let's say I have a json document defined like this:
[
{ "type" : "Type1",
"key1" : "value1" },
{ "type" : "Type2",
"key2" : "value2" }
]
I want to read this json document into a list of strings (List<String>). I only want to read the outer-most list into the Java List, the json objects inside the list should be left as-is inside the list. The result should be equivalent to this (I ignore newlines etc):
var myList = List.of("{\"type\": \"Type1\", \"key1\": \"value1\"}, {\"type\": \"Type2\", \"key2\": \"value2\"}")
Note that I don't want to create any DTO to hold some intermediate representation. I just want everything below the "list" to be represented "as-is".
How can I achieve this?
I'm using Jackson 2.12.1.
If you don't want to hold intermediate representation in a DTO, then one way in which the required deserialization can be achieved is:
// Create a ObjectMapper (of type com.fasterxml.jackson.databind.ObjectMapper)
ObjectMapper mapper = new ObjectMapper();
// Read the json string into a List. This will be deserialized as a collection of LinkedhashMap
List<LinkedHashMap> list = mapper.readValue(getInputString(), List.class);
//Iterate over the deserialized collection and create a JSONObject from every LinkedHashMap
List<String> result = list.stream()
.map(map -> new JSONObject(map).toString())
.collect(Collectors.toList());
This will produce:
[{"key1":"value1","type":"Type1"}, {"key2":"value2","type":"Type2"}]
Downside of this approach is, it takes a hit on performance.

How would I convert an element of a JSONObject to a single element array?

I am using org.json.JSONObject and have a json object defined that was converted from XML. I want to be able to convert one of the elements of the JSON to a single element array, but am unclear on how to do this. For example, say I have the following json:
{
"heading": "value",
"numbers": [1,2,3],
"onevalarray": "MyVal"
}
stored in an org.json.JSONObject object. However, I want the element "onevalarray" to be a single element array:
{
"heading": "value",
"numbers": [1,2,3],
"onevalarray": ["MyVal"]
}
How would I accomplish this?
Call the method getJsonArray in the JSONbject object and specify the name of the property in the JSONObject which has the JSONArray in it like this:
Imagine that myJsonObject has this:
{"heading": "value", "numbers": [1,2,3], "onevalarray": "MyVal"}
And you want a JSONArray with onevalarray data. Try it:
JSONArray jsonArray = myJsonObject.getJSONArray("onevalarray");
Once you have the value of the onevalarray in the onevalarray JSONArray then remove the onevalarray in the original array and the put it again in this way:
myJsonObject.remove("onevalarray");
myJsonObject.put("onevalarray", jsonArray);

Deserialize nested JSON array in Java with Gson

Something like this. http://jsonlint.com/ says it is valid. Json inside {} simplified for this example.
[[0,{"ok":true},[]],[1,{"ok":false},[]]]
Or with indents:
[
[0, {
"ok": true
},
[]
],
[1, {
"ok": false
},
[]
]
]
This is class for object JSONClass.
public class JSONClass {
boolean ok;
}
If I got it right, this JSON string is array of arrays, latter containing some ID, actual JSON data and empty array. How could I deserialize that?
This doesn't work. I also tried making class with subclasses, didn't work out.
JSONClass[] t = g.fromJson(json, JSONClass[].class);
Well, you have an array of arrays here. Gson will let you convert the JSON objects themselves into the class you want - but you'll have to call gson.fromJson() on each of them separately.
Given String json containing your json, something like this should work:
Gson gson = new Gson();
JsonParser jsonParser = new JsonParser();
JsonArray jsonArray = jsonParser.parse(json).getAsJsonArray();
for (JsonElement e: jsonArray) {
JSONClass o = gson.fromJson(e.getAsJsonArray().get(1), JSONClass.class);
}
Essentially, the JsonParser will convert your text into a JsonElement, which is the Gson base class for Json arrays and objects. We can iterate over the elements of the JsonArray which we parsed our text into, which in turn is another array of the format [id, object] - and for each element, take the object portion, and deserialize that into a POJO.

How to Convert List To JsonObject?

This may to possible of duplicate i need to convert the list to jsonobject like this
{"EmailID":"Djlj#sl.com","PhoneNumber":"870796850","ID":2}
like this how can i achieve this so far what i have tried is :
List<CustomerModel> listobj=new ArrayList<CustomerModel>();
listobj=timetrackerdaoobj.Listtoserver();
String gsonString=new Gson().toJson(listobj, collectionType);
In this method am getting jsonarray like this
[{"EmailID":"Djlj#sl.com","PhoneNumber":"870796850","ID":2}]
But i need format like this:
{"EmailID":"Djlj#sl.com","PhoneNumber":"870796850","ID":2}
Try this way,
String gsonString=new Gson().toJson(listobj, collectionType);
gsonString = gsonString.replace("[","").replace("]","");
System.out.println(gsonString); // here you got expected answer
this may helps you.
You want a JSON Object, and not a JSON Array. So pass only your java object and not the list into your Gson converter :
String gsonString = new Gson().toJson(listobj.get(0), yourType);

put method in the json object adds value to the first of the jsonobject;

Consider following piece of code:
JSONObject json = new JSONObject();
json.put("one", 1);
json.put("two", 2);
json.put("three", 3);
If i print the jsonobject it prints like this
{"three":"1","two":"2","one":"1"}
But i want like this.
{"one":"1","two":"2","three":"3"}
Please help. Thanks in advance.
The documentation at http://www.json.org/javadoc/org/json/JSONObject.html says:
A JSONObject is an unordered collection of name/value pairs.
In other words, properties of an object are accessed by name, not by position and the default serialized form does not guarantee any specific order.
Strict positioning comes only with arrays:
JSONArray json = new JSONArray();
json.put("1");
json.put("2");
json.put("3");
json.toString(); // results in ["1", "2", "3"]
The easiest workaround to solve your problem is to use the sortedKeys() method and by iterating the JSONObject key by key, produce the JSON string manually in what ever order necessary. Implementing a custom Comparator might help also.

Categories