JSON Deserialization - JSON Array to ArrayList of JSON Objects - java

I am trying to deserialize a string which is a JSON Array in Java using fasterxml. And I want to convert this into an ArrayList of JSONObjects.
[
{
"test": "hello"
},
{
"anotherTest": "world"
}
]
When I try to use the object mapper as follows,
ArrayList<JSONObject> list = mapper.readValue(sourceString, ArrayList.class);
I am getting an ArrayList which contains LinkedHashMap.
I tried to change my type using the below code.
ArrayList<JSONObject> list = mapper.readValue(s, mapper.getTypeFactory().constructCollectionType(List.class, JSONObject.class));
And even this...
ArrayList<JSONObject> list = mapper.readValue(s,new TypeReference<List<JSONObject>>() {});
Both it did not help me.
Any thoughts?

Related

How to parse a single array, without a name associated with it?

I have the following JSON:
[{
"aaa": "blah",
"ddd": 2
}]
Note that the map is inside an array. How to get the map and then the value of "aaa".
Using Json Simple.
Thanks!
The following code should work. Let me know if it doesn't!
Object obj = JSONValue.parse(jsonString);
JSONArray array = (JSONArray)obj;
JSONObject obj2 = (JSONObject)array.get(0);
String result = obj2.get("aaa")

How to parse arbitrary string of JSON array to a list using Java Jackson

I am trying to use Jackson in Java to parse a string of Json Array in the format of
"[{"key1":"value1"},{"key2":{"keyChild1":"valueChild1","keyChild2","valueChild2"}}]"
However, the JSON object inside the string of array could be any arbitrary valid JSON, which means I cannot map them to any predefined POJO as suggested in Parsing JSON in Java without knowing JSON format
The goal is to convert this string of JSON array to a List<someObject> that can represent each of the JSON inside the array, and this someObject will allow me to add/remove any key/value pairs in that JSON.
I have tried to use
final ObjectMapper objectMapper = new ObjectMapper();
List<JsonNode> jsonNodes = objectMapper.readValue(jsonArraytring, new TypeReference<List<JsonNode>>() {});
and it seems like the List to be empty. I really got stuck here.
Any help would be appreciated.
try
String json = "[{\"key1\":\"value1\"},{\"key2\":{\"keyChild1\":\"valueChild1\",\"keyChild2\":\"valueChild2\"}}]";
ArrayNode array = (ArrayNode) new ObjectMapper().readTree(json);
You can deserialize the JSON array into a list of maps:
ObjectMapper mapper = new ObjectMapper();
String json = "[{\"key1\":\"value1\"},{\"key2\":{\"keyChild1\":\"valueChild1\",\"keyChild2\":\"valueChild2\"}}]";
List<Object> list = mapper.readValue(json, List.class);
list.forEach(o -> {
System.out.println(o);
System.out.println(o.getClass());
});
Which outpurs:
{key1=value1}
class java.util.LinkedHashMap
{key2={keyChild1=valueChild1, keyChild2=valueChild2}}
class java.util.LinkedHashMap
You can push that even further by calling mapper.readValue(json, Object.class). But then you'll need to know how to use the deserialized types.
You can try the following:
JsonNode node = objectMapper.valueToTree(jsonArraytring);
for(JsonNode innerNode : node.elements()){
//here you have each inner object
}

Java: JSON object containing arrays

I have a Java function that loads JSON from a URL and then returns it as a JSONObject
The function I am using is:
json = new JSONObject(jsonString);
from org.json.JSONObject
The problem is that any arrays being contained in the object are just returned as strings, not as arrays.
We also don't know the format of the JSON being included so we can't specifically call a property of the object to parse. It just has to be able to handle any arrays that might exist.
How can I fix this?
You can use Gson for parsing json string. Its clean and easy.
For using Gson, you need to create a class first describing a single response object like this.
public class ResponseObject {
public String id;
public String name;
}
Now as you already have the json string containing an array of objects, parse the json string as follows.
Gson gson = new Gson();
ResponseObject[] objectArray = gson.fromJson(jsonString, ResponseObject[].class);
Simple!
If you still want the JSONObject, the way you retrieve the array is actually..
JSONObject jsonObject = new JSONObject(jsonString);
JSONArray hobbies = jsonObject.getJSONArray("hobbies");
So that
hobbies.getString(0)
hobbies.getString(1)
etc..
JSONArray itself has .get(), getDouble(), getInt(), etc..

passing JSON array from JavaScript to java and convert JSON array to java array

In my application, I need to pass JSON array to java then convert that array to java array using java as a language. Here is the code.
JavaScript
function arraytofile(rans)
{
myData.push(rans); // rans is the random number
var arr = JSON.stringify(myData);// converting to json array
android.arraytofile(arr); // passing to java
}
Java
public void arraytofile(String newData) throws JSONException {
Log.d(TAG, "MainActivity.setData()");
System.out.println(newData);
}
newData is printing data as [[2],[3],[4]]... I want in regular java array. How I can achieve this?
You can use Google gson . An excellent Java library to work with JSON.
Find it here: https://code.google.com/p/google-gson/
Using gson library classes you can do something like this:
// I took a small sample of your sample json
String json = "[[2],[3],[4]]";
JsonElement je = new JsonParser().parse(json);
JsonArray jsonArray = je.getAsJsonArray();
// I'm assuming your values are in String, you can change this if not
List<String> javaArray = new ArrayList<String>();
for(JsonElement jsonElement : jsonArray) {
JsonArray individualArray = jsonElement.getAsJsonArray();
JsonElement value = individualArray.get(0);
// Again, I'm assuming your values are in String
javaArray.add(value.getAsString());
}
Now you have your json as Java List<String>. That's basically as array.
If you know exact number of results, you can surely define an array of fix size and then assign values to it.
If you know Java, than you already know how to go from here.
I hope this helps.

Passing json array in a key value pair

I want to know how to pass the json array as key in a json object.
{
"name" :"Sam",
"grades": [{"maths": "A", "result":"pass"}, {"science": "B", "result":"pass"}]
}
I couldn't pass both the values to 'grades' in jSONObject. I Looped it. But, it simply overwrites the values.
It seems like you are doing something like:
obj.put("grades", mathGrade);
obj.put("grades", scienceGrade);
Where the scienceGrade just overwrites mathGrade.
What you should be doing is using an intermediate array object:
JSONArray grades = new JSONArray();
grades.put(mathGrade);
grades.put(scienceGrade);
obj.put("grades", grades);

Categories

Resources