This question already has answers here:
Why does my ArrayList contain N copies of the last item added to the list?
(5 answers)
Closed 2 years ago.
I try to create the following JSON:
{
"metadata": {
"0": {
"attribute": "technology",
"value": "Ceramics",
"mandatory": "rule"
},
"1": {
"attribute": "color",
"value": "Green",
"mandatory": "rule"
},
"2": {
"attribute": "material",
"value": "Nylon",
"mandatory": "rule"
}
}
}
metadataReq is type JSONObject and it contains the values above
JSONObject obj = new JSONObject();
JSONObject index = new JSONObject();
JSONArray keys = metadataReq.names();
for (int i = 0; i < metadataReq.length (); i++) {
String key = keys.getString (i);
String val = metadataReq.getString (key);
String j = Integer.toString(i);
obj.put("attribute", key);
obj.put("value", val);
obj.put("mandatory", "rule");
index.put(j, obj);
jsonRecipe.put("metadata", index);
}
My script for some reason cause the last object (index #2), to show similar values on the other two objects (#0 and #1)
Using the for loop, how to create it correctly?
The problem in the above code is JSONObject obj = new JSONObject(); initialised only one but you need to create inside the loop.
This code gives the expected output as you want:
public static void main(String[] args) throws JSONException {
JSONObject index = new JSONObject();
JSONObject jsonRecipe = new JSONObject();
JSONObject metadataReq = new JSONObject();
metadataReq.put("technology","Ceramics");
metadataReq.put("material","Nylon");
metadataReq.put("color","Green");
JSONArray keys = metadataReq.names();
for (int i = 0; i < metadataReq.length (); i++) {
String key = keys.getString (i);
String val = metadataReq.getString (key);
String j = Integer.toString(i);
JSONObject obj = new JSONObject();
obj.put("attribute", key);
obj.put("value", val);
obj.put("mandatory", "rule");
index.put(j, obj);
jsonRecipe.put("metadata", index);
}
System.out.println(jsonRecipe);
}
You only created 1 object and inserted it 3 times, as opposed to creating 3 distinct objects.
Related
I try to create a desired json structure in java but I get only last value in json structure since i creating json outside for loop. if i create it in nested for loop then its not give me desired structure of json.
My code is here:-
public static void main(String[] args) {
JSONObject TP1 = new JSONObject();
String[] alias = {"topping","cake"};
String[] entityType = {"Topping","cake"};
String[] textString = {"pizza","pancake"};
String[] usersays_text = {"I want ","I want "};
for(String usy:usersays_text)
{
TP1.put("text",usy.toString());
}
JSONObject TP2 = new JSONObject();
for(String tS:textString)
{
TP2.put("text",tS.toString());
}
for(String eT:entityType)
{
TP2.put("entityType",eT.toString());
}
for(String al:alias)
{
TP2.put("alias",al.toString());
}
JSONArray JSA=new JSONArray();
JSA.put(TP1);
JSA.put(TP2);
JSONObject root1= new JSONObject();
root1.put("parts", JSA);
JSONArray JSA4=new JSONArray();
JSA4.put(root1);
JSONObject root3= new JSONObject();
root3.put("TP", JSA4);
//To print
JSONObject json = new JSONObject(root3.toString()); // Convert text to object
System.out.println(json.toString(4));
}
which results me following json structure:-
{
"TP": [{
"parts": [{
"text": "I want "
},
{
"entityType": "cake",
"alias": "cake",
"text": "pancake"
}
]
}]
}
Desired structure for each value of string array -
for ex:
{
"TP": [
{
"parts": [
{
"text": "I want "
},
{
"alias": "topping",
"text": "pizza",
"entityType": "Topping"
}
]
},
{
"parts": [
{
"text": "I want "
},
{
"alias": "cake",
"entityType": "cake",
"text": "pancake"
}
]
}
]
}
Your jsonobject construction is wrong. In 'jsonobject' key is in unique,
when you try it like this
for(String usy:usersays_text)
{
TP1.put("text",usy.toString());
}
the same key is present in the json object and values get replaced.
Please try the below code, it constructs the json object as expected.
public static void main(String args[]) {
JSONObject TP1 = new JSONObject();
String[] alias = {"topping","cake"};
String[] entityType = {"Topping","cake"};
String[] textString = {"pizza","pancake"};
String[] usersays_text = {"I want ","I want "};
JSONObject jobj = new JSONObject();
JSONArray jarr = new JSONArray();
for(int index = 0; index < usersays_text.length; index++)
{
JSONObject parts = new JSONObject();
JSONArray partsArr = new JSONArray();
JSONObject partsObj = new JSONObject();
partsObj.put("text", usersays_text[index].toString());
JSONObject cont = new JSONObject();
cont.put("alias", alias[index].toString());
cont.put("text", textString[index].toString());
cont.put("entityType", entityType[index].toString());
partsArr.put(partsObj);
partsArr.put(cont);
parts.put("parts", partsArr);
jarr.put(parts);
}
jobj.put("trainingPhrases", jarr);
System.out.println(jobj.toString(4));
}
You have to use single loop, Assume each array has same length, Following code could help you
public static void main(String[] args) throws Exception {
String[] alias = {"topping", "cake"};
String[] entityType = {"Topping", "cake"};
String[] textString = {"pizza", "pancake"};
String[] usersays_text = {"I want ", "I want "};
JSONArray parts = new JSONArray();
for (int i = 0; i < usersays_text.length; i++) {
JSONArray JSA = new JSONArray();
JSONObject TP1 = new JSONObject();
TP1.put("text", usersays_text[i]);
JSONObject TP2 = new JSONObject();
TP2.put("text", textString[i]);
TP2.put("entityType", entityType[i]);
TP2.put("alias", alias[i]);
JSA.put(TP1);
JSA.put(TP2);
parts.put( JSA);
}
JSONObject partsObject = new JSONObject();
partsObject.put("parts",parts);
JSONObject root= new JSONObject();
root.put("trainingPhrases", partsObject);
//To print
JSONObject json = new JSONObject(root.toString()); // Convert text to object
System.out.println(json.toString(4));
}
i have parser function that parse json array and return arrays that i use it in a list adapter and then the adapter is used by a recyclerview .it's giving me the actual length but only the first element of the arrays is filled while the others return NULL
that is my code
public void parsee_item() {
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(json);
final JSONArray userss = jsonObject.getJSONArray(JSON_ARRAY);
item_id = new String[userss.length()];
item_owner = new String[userss.length()];
item_images = new String[userss.length()];
item_names = new String[userss.length()];
item_price = new String[userss.length()];
item_place = new String[userss.length()];
JSONObject jo = null;
for (int i = 0; i < userss.length();i++) {
jo = userss.getJSONObject(i);
Log.d("alrsp", jo.toString());
item_id[i] = jo.getString(KEY_ID);
item_owner[i] = jo.getString(KEY_OWNER);
item_images[i] = jo.getString(KEY_IMAGE);
item_names[i] = jo.getString(KEY_NAME);
item_price[i] = jo.getString(KEY_PRICE);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
the json is
{
"result": [{
"item_id": "10",
"owner": "user",
"item_type_id": "1",
"url1": "http:\/\/localhost:8080\/market\/items\/14.1.png",
"name": "jc",
"price": "76"
}, {
"item_id": "12",
"owner": "user",
"item_type_id": "1",
"url1": " http:\/\/localhost:8080\/market\/items\/14.1.png",
"name": "nzbsbsb",
"price": "0"
}, {
"item_id": "13",
"owner": "user",
"item_type_id": "1",
"url1": " http:\/\/localhost:8080\/market\/items\/14.1.png",
"name": "uygf",
"price": "0"
}]
}
and this screenshot of the list
enter image description here
it's not suggested parsing json yourself ,use a Json Parse Util such as Gson or fastJson instead .
I used your code, debug, and found values are updated their is no error with JSON paring, So check your recycler view adapter code or share it
Replace this line
jo = userss.getJSONObject(4);
with this
jo = userss.getJSONObject(i);
JSONObject jo = null;
for (int i = 0; i < userss.length();i++) {
jo = userss.getJSONObject(i);
Log.d("alrsp", jo.toString());
item_id[i] = jo.getString(KEY_ID);
item_owner[i] = jo.getString(KEY_OWNER);
item_images[i] = jo.getString(KEY_IMAGE);
item_names[i] = jo.getString(KEY_NAME);
item_price[i] = jo.getString(KEY_PRICE);
item_place[i] = jo.getString("place");
}
the problem with ur code is you use hardcode value 4
jo = userss.getJSONObject(4);
insted of this use
jo = userss.getJSONObject(i);
at each and every time you are parsing the index 4 jsonObject information
public void parsee_item() {
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(json);
final JSONArray userss = jsonObject.getJSONArray(JSON_ARRAY);
item_id = new String[userss.length()];
item_owner = new String[userss.length()];
item_images = new String[userss.length()];
item_names = new String[userss.length()];
item_price = new String[userss.length()];
item_place = new String[userss.length()];
JSONObject jo = null;
for (int i = 0; i < userss.length();) {
jo = userss.getJSONObject(i);
Log.d("alrsp", jo.toString());
item_id[i] = jo.getString(KEY_ID);
item_owner[i] = jo.getString(KEY_OWNER);
item_images[i] = jo.getString(KEY_IMAGE);
item_names[i] = jo.getString(KEY_NAME);
item_price[i] = jo.getString(KEY_PRICE);
item_place[i] = jo.getString("place");
i++;
}
} catch (JSONException e) {
e.printStackTrace();
}
}
if you use this type of parsing it may lead to null pointer exception
You can parse above JSON as follows
private void jsonParse(String response) throws JSONException {
JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.getJSONArray("result");
if (jsonArray != null && jsonArray.length() > 0) {
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject object = jsonArray.getJSONObject(i);
if (object != null) {
String itemId = object.getString("item_id");
String owner = object.getString("owner");
String item_type_id = object.getString("item_type_id");
String url1 = object.getString("url1");
String name = object.getString("name");
String price = object.getString("price");
}
}
}
}
i was receiving a parameter that wasn't being sent by the jsonarray
item_place[i] = jo.getString("place")
I'm getting this string (from webservice) into a JSONArray,
[{
"textinput": [{
"position": 0,
"dependency": "no",
"id": 0,
"Itype": "textinput"
}, {
"position": 2,
"dependency": "no",
"id": 1,
"Itype": "textinput"
}]
}, {
"textarea": [{
"position": 1,
"type": "textarea",
"dependency": "no",
"id": 0
}]
}]
I need to sort the array by ascending order based on key-"position"
I am using org.json library, the below code is the one so far the code i used
JSONArray sortedJsonArray = new JSONArray();
List<JSONObject> jsonList = new ArrayList<JSONObject>();
for (int i = 0; i < jsonArray.length(); i++) {
jsonList.add(jsonArray.getJSONObject(i));
}
Collections.sort( jsonList, new Comparator<JSONObject>() {
public int compare(JSONObject a, JSONObject b) {
String valA = new String();
String valB = new String();
try {
valA = (String) a.get("position");
valB = (String) b.get("position");
}
catch (JSONException e) {
//do something
}
return valA.compareTo(valB);
}
});
for (int i = 0; i < jsonArray.length(); i++) {
sortedJsonArray.put(jsonList.get(i));
}
AALso tried other links in the site.
please help
Try TreeMap, it will automatically sort the array for you. All you have to do is make "position" the Key of TreeMap and JSONObject the value. The treemap will arrange the values in ascending order of the keys.And then you can retrieve the JSONObject values from the treemap.
private TreeMap<Integer,JSONObject> sortedarray = new TreeMap<Integer,JONObject>();
for (int i = 0; i < jsonArray.length(); i++) {
try {
sortedarray.put(Integer.parseInt(jsonArray.getJSONObject(i).get("position")+""),jsonArray.getJSONObject(i));
} catch (JSONException e) {
e.printStackTrace();
}
}
Now if you want it to be a jsonArray only..
JSONArray sortedJsonArray = new JSONArray();
for(int x = 0; x<sortedarray.size();x++)
{
//assuming that positions you get in JSON are always complete like 1,2,3,4,....,10,...,100.
sortedJsonArray.put(sortedarray.get(x));
//assuming that positions you get in JSON are not always complete like 1,3,4,..,10,13,...,100.( misses a few numbers in between like 2 and 11 in this case)
sortedJsonArray.put(sortedarray.get(Integer.parseInt(advanceplay.get(advanceplay.keySet().toArray()[i]))));
}
I Have such kind of JSON string:
[{
"id": 3,
"city": "Ilmenau",
"floor": null,
"housenumber": "35",
"streetname": "Blumenstraße",
"zip": "98693"
}, {
"id": 4,
"city": "Berlin",
"floor": null,
"housenumber": "54",
"streetname": "Bogdansplatz",
"zip": "194354"
}]
And I need it to be parsed into two-dimensional array that will look like this:
enter image description here
How can I make it, using GSON java library?
Now I have only written this piece of code, that returns a list:
String s=getJson("SELECT * FROM address;");
JsonParser jsonParser = new JsonParser();
JsonObject jo = (JsonObject)jsonParser.parse(s);
JsonArray jsonArr = jo.getAsJsonArray("array");
//jsonArr.
Gson googleJson = new Gson();
ArrayList jsonObjList = googleJson.fromJson(jsonArr, ArrayList.class);
System.out.println("List size is : "+jsonObjList.size());
System.out.println("List Elements are : "+jsonObjList.toString());
But the code above works only with JSON object of array, not with string I have shown above.
Could you please try the following and see the results:
// String 's' holds the JSON
JsonParser jsonParser = new JsonParser();
JsonArray jsonArray = (JsonArray) jsonParser.parse(s);
// this object is used to get the keys
JsonObject firstJsonObject = jsonArray.get(0).getAsJsonObject();
Set<java.util.Map.Entry<String, JsonElement>> entrySet = firstJsonObject.entrySet();
// declare two dimensional array
Object[][] array = new Object[entrySet.size()][jsonArray.size() + 1];
// the first column of the two-dimensional array is populated
Iterator<java.util.Map.Entry<String, JsonElement>> itr = entrySet.iterator();
for (int i = 0; itr.hasNext(); i++) {
array[i][0] = itr.next().getKey();
}
// the rest of the columns are populated
for (int i = 0; i < jsonArray.size(); i++) {
JsonObject obj = (JsonObject) jsonArray.get(i);
for (int j = 0; j < array.length; j++) {
String key = array[j][0].toString();
JsonElement value = obj.get(key);
array[j][i + 1] = value instanceof JsonNull ? null : value.getAsString();
}
}
// now the two dimensional array is fully populated
I have a JSON response which look something like this( its different from user to user)
{
"success": true, "data":
[
{
"mandatory_tag": "My Company",
"id": "topic_1408946825893148"
},
{
"mandatory_tag": "Partners",
"id": "topic_1408946942491149",
},
{
"mandatory_tag": "Industry",
"id": "topic_1408946996510150",
},
{
"mandatory_tag": "Competitors",
"id": "topic_1409210454810358",
},
{
"mandatory_tag": "Competitors",
"id": "topic_1408947133657152"
},
{
"mandatory_tag": "Competitors",
"id": "topic_1408947071457151",
},
{
"mandatory_tag": "Competitors",
"id": "topic_1409210621754362",
},
{
"mandatory_tag": "Competitors",
"id": "topic_1409210704390363",
},
{
"mandatory_tag": "Competitors",
"id": "topic_1409210794791364"
}
]
}
I am parsing it and trying to store in HashMap, but the key value is duplicating. Can anyone suggest me how can i store all id with same mandatory_tag in one array?
I am new to this so please consider..thanks
try
{
JSONObject jsonMain = new JSONObject(jsonString);
JSONArray dataArray = jsonMain.getJSONArray("data");
for(int i = 0; i < dataArray.length(); i++)
{
JSONObject tagObject = dataArray.getJSONObject(i);
String mandatory_tag = tagObject.getString("mandatory_tag");
String id = tagObject.getString("id");
List<String> arrayID = new ArrayList<String>();
if(myMap.containsKey(mandatory_tag))
{
arrayID.add(id);
myMap.put(mandatory_tag, arrayID);
} else
{
List<String> newArrayID = new ArrayList<String>();
newArrayID.add(id);
myMap.put(mandatory_tag, newArrayID);
}
}
And well i got stuck at this now..any good logic please..
A hashmap allows you to store key-value items. I would suggest the HashMap be of type <String,List<String>> so allowing you to store items with the same mandatory_tag in the same list under 1 key.
For example
HashMap<String,List<String>> myMap = new HashMap<String,List<String>>();
if (myMap.containsKey(mandatory_tag)) {
List<String> values = myMap.get(mandatory_tag);
if (values!=null) {
values.add(id)
} else {
values = new List<String>();
values.add(id);
}
}
Update
As I wrote in my comment below, the except you added has an error
List<String> arrayID = new ArrayList<String>();
if(myMap.containsKey(mandatory_tag))
{
arrayID.add(id);
myMap.put(mandatory_tag, arrayID);
}
What you are doing here is, if the map already contains the key you are replacing the value associated with the key with a new list which contains only 1 value. What you need to do is update the list of already existing values. Check the code below and make sure you understand the problem. These are fundamentals of programming and you need to understand the logic of what you're doing to advance.
//Somewhere you have declared your HashMap
HashMap<String,List<String>> myMap = new HashMap<String,List<String>>();
//then we continue with your excerpt
try {
JSONObject jsonMain = new JSONObject(jsonString);
JSONArray dataArray = jsonMain.getJSONArray("data");
for(int i = 0; i < dataArray.length(); i++) {
JSONObject tagObject = dataArray.getJSONObject(i);
String mandatory_tag = tagObject.getString("mandatory_tag");
String id = tagObject.getString("id");
if(myMap.containsKey(mandatory_tag)) {
List<String> arrayID = myMap.get(mandatory_tag);
arrayID.add(id);
} else {
List<String> newArrayID = new ArrayList<String>();
newArrayID.add(id);
myMap.put(mandatory_tag, newArrayID);
}
}
Create a POJO called TagValues(or whatver name you would like) with variables mandatory_tag,id and then and create an ArrayList<TagValues> in which you can store all the objects.
Thanks for your response, but with help of you guys, i got the solution
`HashMap<String,List<String>> myMap = new HashMap<String,List<String>>();
for(int i = 0; i < dataArray.length(); i++)
{
JSONObject tagObject = dataArray.getJSONObject(i);
String mandatory_tag = tagObject.getString("mandatory_tag");
String id = tagObject.getString("id");
if(myMap.isEmpty())
{
arrayID = new ArrayList<String>();
arrayID.add(id);
myMap.put(mandatory_tag, arrayID);
}
else if(myMap.containsKey(mandatory_tag))
{
arrayID.add(id);
myMap.put(mandatory_tag, arrayID);
}
else
{
arrayID = new ArrayList<String>();
arrayID.add(id);
myMap.put(mandatory_tag, arrayID);
}
}`
In those cases, I'd like to use a custom HashMap:
public MMap getData() {
MMap result = new MMap();
JSONArray array = getJSONArrayFromTotalJSON();
for (int i = 0; i < array.length(); i++) {
JSONObject obj = array.getJSONObject(i);
String mtag = obj.getString(MANDATORY_TAG);
String id = obj.getString(ID);
result.put(mtag, id);
}
return result;
}
public class MMap extends HashMap<String, List<String>> {
public void put(String key, String value) {
if (!this.containsKey(key))
this.put(key, new ArrayList<String>());
this.get(key).add(value);
}
}