Passing json array in a key value pair - java

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

Related

How to put data to parsed JSONObject

i have some parse code and to parsed JSONObject i need to add one more JSONObject, but getting error Unexpected token LEFT BRACE({), because my code creating multiply JSONObjects in file, not at parsed JSONObjec. Here is a code, that creating object
aJson = (JSONObject) parser.parse(reader);
JSONObject json = new JSONObject();
JSONArray blockData = new JSONArray();
for(Block b : blocks){
json.put("player-name", p.getName());
json.put("uuid", p.getUniqueId().toString());
json.put("nearestPlayers", new JSONArray());
blockData.add(b.getLocation().getWorld().getName());
blockData.add(b.getLocation().getWorld().getEnvironment());
blockData.add(b.getLocation().getX());
blockData.add(b.getLocation().getY());
blockData.add(b.getLocation().getZ());
}
aJson.put(blockData, json);
Here is JSON
{"[\"world\",NORMAL,-23.0,67.0,75.0]":{"player-name":"MisterFunny01","nearestPlayers":[],"uuid":"206d32da-bf72-3cfd-9a26-e374dd76da31"}} //here is that part// {"[\"world\",NORMAL,-23.0,67.0,75.0]":{"player-name":"MisterFunny01","nearestPlayers":[],"uuid":"206d32da-bf72-3cfd-9a26-e374dd76da31"},"[\"world\",NORMAL,-23.0,67.0,75.0]":{"player-name":"MisterFunny01","nearestPlayers":[],"uuid":"206d32da-bf72-3cfd-9a26-e374dd76da31"}}
In JSON array values must be of type string, number, object, array, boolean or null. Arrays hold values of the same type and not different types.
Looking at your code the array is an array of objects. So you would have to create an object and add the values before adding to the array.
Don't directly add values to the array but create an object and then add to the array.
Your code is wrong. To put an object into JSONObject please read this document
In your case, you need to convert blockData to String to put in the JSONObject.
It's like this: aJson.put(blockData as String, json);
Hope it can be helpful to you.

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 iterate over json Array having multiple json objects with different header

I am getting an json array from rest webservice in response which is like
[{
"mutualFund":{"fundCode":"XYZ","fundName": "Funds - Global Income
Fund (G)-SGD","isin":"LU0882574725","sedol":"1234"}},
{"brokers":{"fundID":"abcd","fundName":"Funds - Focus
Fund A-USD","isin":"LU0197229882","sedol":"6543"}
}]
I am trying to iterate over all mutualFund arrays attributes to fetch their value. I have tried this code snippet but its returning error --"mutualFund do not exist". In my json file some objects are of mutualfund type and some are of other type with different attributes so I had to iterate and differentiate between both of them . So I cant use getJSONObject(i).
JSONArray jsonArray=new JSONArray(response.getBody());
for(int i=0;i<jsonArray.length();i++){
JSONObject jsonObject=jsonArray.getJSONObject("mutualFund");
}
Based on the classes and methods you're using, I'm assuming you use org.primefaces.json classes. But even if you're using a different API, the logic will be basically the same.
First of all, look at your JSON structure:
[
{
"mutualFund": {
"fundCode": "XYZ",
"fundName": "Funds-GlobalIncomeFund(G)-SGD","isin":"LU0882574725","sedol":"1234"
}
},
{
"brokers": {
"fundID": "abcd",
"fundName": "Funds-FocusFundA-USD","isin":"LU0197229882","sedol":"6543"
}
}
]
It's an array with 2 elements. The first element is an object with just one key (mutualFund) and its value (another object with fundCode and fundName keys). Note that the object has a mutualFund key, and you're trying to get it as if the object itself was a mutualFund. That's what causes the error.
So, to get all mutualFund objects, you need to check every element in the array, and for each element you must check if it has a mutualFund key. Then your code will be like this:
for (int i = 0; i < jsonArray.length(); i++) {
// get object i
JSONObject jsonObject = jsonArray.getJSONObject(i);
// check if object has mutualFund key
if (jsonObject.has("mutualFund")) {
// get mutualFund object and do something with it
JSONObject mutualFund = jsonObject.getJSONObject("mutualFund");
// do something with mutualFund object (you can get values for fundCode and fundName keys, etc)
}
}
Note: if you're using a different JSON API, the methods names might differ (instead of has, some uses containsKey, or get(key) != null, but the logic to find mutualFund objects will be the same).

JAVA JSONArray sort in reverse order

I have JSON array like this:
[{"BMW": [], "OPEL": [], "Mercedes": []}]
and I want to get
[{"Mercedes": [], "OPEL": [], "BMW": []}]
How can I make like this?
Since JSONObjects are not keeping their order in which you build them (has to do with how it's handled in memory) you should refactor the data.
[{"BMW": [], "OPEL": [], "Mercedes": []}]
to
[{"BMW":[]}, {"OPEL":[]}, {"Mercedes":[]}]
That still won't help you right away though since JSONArray in java doesn't appear to have reverse() method :(
So like I commented: build a new JSONArray in reverse order:
JSONArray newJsonArray = new JSONArray()
for (int i = jsonArray.length()-1; i>=0; i--) {
newJsonArray.put(jsonArray.get(i));
}
A small yet best solution to this is to store the JSON array in reverse order:
JSONArray array = response.getJSONArray("records");
for (int i = array.length()-1; i >= 0; i--) {
// Perform your regular JSON Parsing here
}
You dont need to edit / change your JSON
You have a JSON object, not an array. An object is comprised of key-value pairs, but these pairs are not ordered by key in any way. In fact, the order should not matter - the representation is the same.
From the ECMAScript spec, as copied here: http://interglacial.com/javascript_spec/a-4.html
4.3.3 Object An object is a member of the type Object. It is an unordered collection of properties each of which contains a primitive
value, object, or function. A function stored in a property of an
object is called a method.

parse json data already in an array?

I have the following data:
[{"class":"test","description":"o hai","example":"a","banana":"b"}]
As this JSON data is already in an array, I'm having troubles to parse this with JSON simple:
File file = new File( "/Users/FLX/test.json");
String s = FileUtils.readFileToString(file);
Object obj = parser.parse(s);
JSONArray array = (JSONArray) obj;
log.warn("WAAAAT"+array.get(1));
This doesn't work because "1" (description) is in array 0, which causes an out of bounds exception, how can I properly do this?
[] denotes an array, while {} denotes an object, so you have an array of objects.
The way your JSON is formatted, you have an array which contains a single object. That single object has properties named "class", "description", "example", and "banana" with values "test", "o hai", "a", and "b" respectively.
JSONArray is 0 based so array.get(1) would be out of bounds. In order to get description you would do something like array.getJSONObject(0).get("description")

Categories

Resources