Adding second json object to same json array in java [duplicate] - java

This question already has answers here:
Add data to JSONObject
(3 answers)
Closed 9 years ago.
Whenever I add second JSONObject to JSONArray, it overwrites the previous array object value.
My java servlet code is-
JsonArray ja=new JsonArray();
JsonObject j;
j = new JsonObject();
j.add("uid", j);
j.add("fname", j);
j.add("lname", j);
for(int i=0;i<uid_list.size();i++){
out.println(uid_list.get(i).toString());
out.println(fname_list.get(i).toString());
out.println(lname_list.get(i).toString());
j.addProperty("uid", uid_list.get(i).toString());
j.addProperty("fname", fname_list.get(i).toString());
j.addProperty("lname", lname_list.get(i).toString());
ja.add(j);
out.println(ja.toString());
}
out.println(ja.toString());
and the output is:
abc bcd cde [{"uid":"abc","fname":"bcd","lname":"cde"}] xyz wxy uyw [{"uid":"xyz","fname":"wxy","lname":"uyw"},{"uid":"xyz","fname":"wxy","lname":"uyw"}] [{"uid":"xyz","fname":"wxy","lname":"uyw"},{"uid":"xyz","fname":"wxy","lname":"uyw"}]
can someone please give me solution for this

You are modifying the same instance of JsonObject in the loop. Create new JsonObject in loop,
for(int i=0;i<uid_list.size();i++){
j=new JsonObject();
out.println(uid_list.get(i).toString());

Related

JSONArray.add(JSONObject) in for loop is replacing old values in for loop and Array consists of the last values in the loop

Hi Below is a simple method which I am using to dynamically generate the JSON request based on Array length from some other API response.
However inside the for loop everything seems to work fine except at the end when JSONArray.add is called, it replaces old jsonObject values inside the array to a new one, and at the end whole array consists of the only same set of JSON objects.
After a lot of debugging can't find the solution, is due to a variable declaration or something. Below is the method I am using
For ref: I am using minidev.JSON
public JSONObject method1(JSONObject sampleJsonObjTemplate, String responseofotherapi) {
JSONArray jsonArray = JsonPath.parse(responseofotherapi).read("$.columns");
JSONArray dataSetColumnArray = new JSONArray();
JSONArray currentJsonColumnArr= JsonPath.parse(dataSetObj).read("$.columns");
JSONObject currentJsonColumnObject= (JSONObject) currentJsonColumnArr.get(0);
LinkedHashMap<String,Object> currentColumn;
for(int columnNumber = 0; columnNumber < jsonArray.size(); columnNumber++){
currentColumn= (LinkedHashMap<String,Object>)jsonArray.get(columnNumber);
String name = currentColumn.get("name").toString();
currentJsonColumnObject.put("name",name);
currentJsonColumnObject.put("alias",name+" Column Alias ");
currentJsonColumnObject.put("description",name+" Column Description ");
dataSetColumnArray.add(columnNumber,currentJsonColumnObject);
currentColumn.clear();
}
JSONObject updatedDataSetReq=JsonPath.parse(dataSetObj).set("$.columns",dataSetColumnArray).json();
return updatedDataSetReq;
}
The problem is with your currentJsonColumnObject object assigning in for loop.
you are using the same object currentJsonColumnObject for all iterations which is referring to currentJsonColumnArr.get(0).
To solve your issue you need to set a different object for currentJsonColumnObject.
JSONArray jsonArray = JsonPath.parse(responseofotherapi).read("$.columns");
JSONArray dataSetColumnArray = new JSONArray();
JSONArray currentJsonColumnArr= JsonPath.parse(dataSetObj).read("$.columns");
//object will be set inside loop
JSONObject currentJsonColumnObject;
LinkedHashMap<String,Object> currentColumn;
for(int columnNumber = 0; columnNumber < jsonArray.size(); columnNumber++){
currentColumn= (LinkedHashMap<String,Object>)jsonArray.get(columnNumber);
// getting object from `currentJsonColumnArr` instead of using the same.
currentJsonColumnObject= (JSONObject) currentJsonColumnArr.get(columnNumber);
String name = currentColumn.get("name").toString();
currentJsonColumnObject.put("name",name);
currentJsonColumnObject.put("alias",name+" Column Alias ");
currentJsonColumnObject.put("description",name+" Column Description ");
dataSetColumnArray.add(columnNumber,currentJsonColumnObject);
currentColumn.clear();
}

how to convert hashmap values to string [duplicate]

This question already has answers here:
How do I print my Java object without getting "SomeType#2f92e0f4"?
(13 answers)
Closed 5 years ago.
The following code is printing hash values instead of Array
JSONObject myjson1 = new JSONObject(expectedResult);
Iterator x = myjson1.keys();
JSONArray jsonArray = new JSONArray();
while (x.hasNext()){
String key = (String) x.next();
jsonArray.put(myjson1.get(key));
System.out.println(x);
}
The output is as follows:
java.util.HashMap$KeyIterator#42a0b130
java.util.HashMap$KeyIterator#3c2a5fb9
java.util.HashMap$KeyIterator#6e68bc46
java.util.HashMap$KeyIterator#3223cb64
java.util.HashMap$KeyIterator#256c426b
PS: Converting Json to Array (key : value) form
Do not use (String) instead use toString()
So
String key = (String) x.next();
jsonArray.put(myjson1.get(key));
System.out.println(x.toString());
And if you want to convert it to string array:
String[] result = jsonArray.values().toArray(new String[0]);
And you can check this one:
how to covert map values into string in Java
I suggest you to use Gson library to manage .json files. It's more accurate, it's more user-friendly and it works very well.
By the way you're asking Java to print the object "x" (Iterator). An object contains the reference to the memory allocation of itself.
You have to ask your software to convert it in a human-readable format, such as String is.
So try to add .toString() method after x invocation.
Try to do something like:
JSONObject myjson1 = new JSONObject(expectedResult);
Iterator x = myjson1.keys();
JSONArray jsonArray = new JSONArray();
while (x.hasNext()){
String key = (String) x.next();
jsonArray.put(myjson1.get(key));
System.out.println(x.toString());
}
I hope to be helpful.

how to create json array from java string for loop

I have a JAVA for loop which prints the out put as shown below.
inside for loop::{"state":"tess","path":"/content/projectpath/en/men"} inside for loop::{"state":"hello","path":"/content/projectpath/en/women"}
Any my code snippet is as shown below.
for (Value val : values) {
//jsonobj = new JSONObject(val.getString());
out.println("inside for loop::" + val.getString());
// JSONArray jsonarr = val.getString();
}// out.println("::"+jsonobj.toString());
How to get a JSON Array after the for loop which should have the values {"state":"tess","path":"/content/projectpath/en/men"} and {"state":"hello","path":"/content/projectpath/en/women"}
create a JSONArray like this. insert your looping object on list. Finally you will get an array please try it.
JSONArray list = new JSONArray();
list.add(val);

Get jsonarray key name [duplicate]

This question already has answers here:
Get json array keys in android
(5 answers)
Closed 7 years ago.
I need to get a key name of JsonArray, so JSON looks like this, please not, that JSON is starting with array brackets, and inside it it has objects, that was made i guess because back end will have the ability to add objects.
[
{
"tehnology": [ ]
},
{
"science": []
}
]
So i need to get the names from it "technology" and "science", because json can dynamically change, how can I implement it?
The JSONArray contains JSONObjects. Retrieve every JSONObject and use keys() to access the key defined in every JSONObject
JSONArray jArray = new JSONArray(response);
for (int i = 0; i < jArray.length(); i++) {
JSONObject object = jArray.optJSONObject(i);
Iterator<String> iterator = object.keys();
while(iterator.hasNext()) {
String currentKey = iterator.next();
}
}

Gson parse json array of length 1 into JsonArray object instead of JsonObject object [duplicate]

This question already has answers here:
Gson handle object or array
(4 answers)
Closed 7 years ago.
Using Gson, I am trying to force my json objects to have an array value with one element. Although I construct the json this way, the JsonParser creates a new JsonObject in place of my array of length 1. The majority of json in my system have value with arrays greater than length 1 and parse correctly.
I discovered this while attempting a utility method for brute forcing a JsonObject to JsonArray. It's not working out as I would expect.
static JsonArray bruteForceJsonArray(JsonObject object, String key) {
if(object.get(key).isJsonArray()) {
return object.get(key).getAsJsonArray();
} else {
System.out.println("broken: " + object.toString());
JsonObject temp = object.get(key).getAsJsonObject();
String fixed = "{'" + key + "':[" + temp.toString() + "]}";
System.out.println("pre-fix: " + fixed);
//parsing here reduces the array to an object - hot to prevent?
temp = new JsonParser().parse(fixed).getAsJsonObject();
System.out.println("fixed: " + object.toString());
return object.get(key).getAsJsonArray();
}
}
output:
broken: {"token":{"NER":"O","id":1.0,"word":".","CharacterOffsetEnd":765.0,"Speaker":"PER0","POS":".","lemma":".","CharacterOffsetBegin":764.0}}
pre-fix: {'token':[{"NER":"O","id":1.0,"word":".","CharacterOffsetEnd":765.0,"Speaker":"PER0","POS":".","lemma":".","CharacterOffsetBegin":764.0}]}
fixed: {"token":{"NER":"O","id":1.0,"word":".","CharacterOffsetEnd":765.0,"Speaker":"PER0","POS":".","lemma":".","CharacterOffsetBegin":764.0}}
An example of the majority json as they appear correctly in the system:
{"token":[{"Speaker":"PER0","POS":"IN","lemma":"except","CharacterOffsetBegin":742.0,"NER":"O","id":1.0,"word":"Except","CharacterOffsetEnd":748.0},{"CharacterOffsetEnd":752.0,"Speaker":"PER0","POS":"IN","lemma":"for","CharacterOffsetBegin":749.0,"NER":"O","id":2.0,"word":"for"},{"id":3.0,"word":"extra","CharacterOffsetEnd":758.0,"Speaker":"PER0","POS":"JJ","lemma":"extra","CharacterOffsetBegin":753.0,"NER":"O"},{"Speaker":"PER0","POS":"NN","lemma":"meat","CharacterOffsetBegin":759.0,"NER":"O","id":4.0,"word":"meat","CharacterOffsetEnd":763.0},{"CharacterOffsetEnd":764.0,"Speaker":"PER0","POS":".","lemma":".","CharacterOffsetBegin":763.0,"NER":"O","id":5.0,"word":"."}]}
Is there a clever way out of this problem - some way I can effectively force my objects into arrays so I can process them in stream without too much try/catch or if/else handling?
static JsonArray bruteForceJsonArray(JsonObject object, String key) {
if (object.get(key).isJsonArray()) {
return object.get(key).getAsJsonArray();
} else {
JsonArray oneElementArray = new JsonArray();
oneElementArray.add(new JsonObject());
return oneElementArray;
}
}
Although, you shouldn't work with JsonObject/JsonArray directly. Make a POJO class for your data and use Gson to deserialize JSON.

Categories