Put JSONObjet into JSONArray - java

I have a problem putting JSONObject into JSONArray.
Here is my code:
String strObject = "{\"Code\":\"a\", \"Name\": \"b\"}";
JSONObject anExistedObject = new JSONObject(strObject);
JSONArray myArray = new JSONArray();
for(int count = 0; count < 2; count++){
JSONObject myObject = new JSONObject;
myObject = anExistedObject;
myObject.put("Count", count);
myArray.put(myObject);
}
System.out.println(myArray.toString());
Result:
[
{
"Code": "a",
"Name": "b",
"Count": 1
},
{
"Code": "a",
"Name": "b",
"Count": 1
}
]
What I expected:
[
{
"Code": "a",
"Name": "b",
"Count": 0
},
{
"Code": "a",
"Name": "b",
"Count": 1
}
]
I've read this post but still don't know how to fix mine.
Did I missed something?

You each time modify same object because of line: myObject = anExistedObj;
You need make copy of that object instead.
Correct code:
JSONObject anExistedObj = new JSONObject();
myObject.put("Code", "a");
myObject.put("Name", "a");
JSONArray myArray = new JSONArray();
String[] keys = JSONObject.getNames(anExistedObj);
for(int count = 0; count < 2; count++){
JSONObject myObject = new JSONObject(anExistedObj, keys);
//anExistedObj = {"Code":"a", "Name": "b"}
myObject.put("Count", count);
myArray.put(myObject);
}
System.out.println(myArray.toString());
Checkout documentation of copy constructor JSONObject

You are updating and reusing anExistedObject everytime
String strObject = "{\"Code\":\"a\", \"Name\": \"b\"}";
JSONArray myArray = new JSONArray();
for(int count = 0; count < 2; count++){
JSONObject myObject = new JSONObject(strObject);
myObject.put("Count", count);
myArray.put(myObject);
}
System.out.println(myArray.toString());

This happens because the line myObject.put("Count", count); always modifies the same object since the variable is only a reference to the object itself. Meaning that myObject and anExistedObject point to the same object.
You should create a copy with:
JSONObject copy = new JSONObject(original, JSONObject.getNames(original));
Instead of using:
JSONObject myObject = new JSONObject;
myObject = anExistedObj;

Related

Get specific index of JSON Nested objects in java Android

How I can get only the "name" string of every object under "fields" Array, of main Array index at 0 & then next index using loop or with something super idea
[
{
"name": "Bank1",
"fields": [
{
"name": "Email",
"slug": "email",
"type": "input"
},
{
"name": "City",
"slug": "city",
"type": "input"
},
{
"name": "Screenshot",
"slug": "screenshot",
"type": "file"
},
{
"name": "Full Name",
"slug": "full-name",
"type": "input"
}
],
"status": "Active"
},
{
"name": "Bank2",
"fields": [
{
"name": "Email",
"slug": "email",
"type": "input"
},
{
"name": "City",
"slug": "city",
"type": "input"
},
{
"name": "Screenshot",
"slug": "screenshot",
"type": "file"
},
{
"name": "Submitted Date",
"slug": "submitted-date",
"type": "calendar"
}
],
"status": "Active"
}
]
Output I want:
Email
City
Screenshot
Full Name
Means in the output, I have got index 0, first object array data...
What I have done yet
public void onResponse(String response) {
try {
JSONArray jsonArray = new JSONArray(response);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String p_name = jsonObject.getString("name");
ArrayList<String> arr = new ArrayList<>();
JSONArray ja = jsonObject.getJSONArray("fields");
int len = ja.length();
for (int j = 0; j < len; j++) {
JSONObject json = ja.getJSONObject(j);
arr.add(json.getString("name"));
}
}}catch block...
this gives me all indexes name data i want only specific index data
My Current Output:
Email
City
Screenshot
Full Name
Email
City
Screenshot
Submitted Date
If you want to get specific index data then you should pass if condition in for loop.
EX: to get output of index 0 like,
Email
City
Screenshot
Full Name
Your code would be like below.
public void onResponse(String response) {
try {
JSONArray jsonArray = new JSONArray(response);
for (int i = 0; i < jsonArray.length(); i++) {
if(i==0){
JSONObject jsonObject = jsonArray.getJSONObject(i);
String p_name = jsonObject.getString("name");
ArrayList<String> arr = new ArrayList<>();
JSONArray ja = jsonObject.getJSONArray("fields");
int len = ja.length();
for (int j = 0; j < len; j++) {
JSONObject json = ja.getJSONObject(j);
arr.add(json.getString("name"));
}
}
}}catch block...
int i=gotIndex;//here you can give your exact index that you want
JSONObject jsonObject = jsonArray.getJSONObject(i);
String p_name = jsonObject.getString("name");
ArrayList<String> arr = new ArrayList<>();
JSONArray ja = jsonObject.getJSONArray("fields");
int len = ja.length();
for (int j = 0; j < len; j++) {
JSONObject json = ja.getJSONObject(j);
arr.add(json.getString("name"));
}
here you used the loop you can use the json object out side the loop with using the index number i (jsonObject = jsonArray.getJSONObject(i))

Sorting JSON array by ID

I wrote code that takes a string that holds a JSON data. I'm sorting my JSON object array by ID. When I'm using my method I get this exception: "org.json.JSONException: A JSONArray text must start with '[' at 1 [character 2 line 1]".
What am I missing here and how to solve it?
private static void ResortJsonByUseCaseID( String jsonArrStr )
{
JSONArray jsonArr = new JSONArray(jsonArrStr);
JSONArray sortedJsonArray = new JSONArray();
List<JSONObject> jsonValues = new ArrayList<JSONObject>();
for (int i = 0; i < jsonArr.length(); i++) {
jsonValues.add(jsonArr.getJSONObject(i));
}
java.util.Collections.sort( jsonValues, new java.util.Comparator<JSONObject>() {
private static final String KEY_NAME = "useCaseId";
#Override
public int compare(JSONObject a, JSONObject b) {
String valA = new String();
String valB = new String();
try {
valA = (String) a.get(KEY_NAME);
valB = (String) b.get(KEY_NAME);
}
catch (JSONException e) {
//do something
int tal = 9;
}
return valA.compareTo(valB);
}
});
for (int i = 0; i < jsonArr.length(); i++) {
sortedJsonArray.put(jsonValues.get(i));
}
jsonArrStr = sortedJsonArray.toString();
}
The code you are describing will only work on a json that looks something like this:
[
{ "useCaseId" : "4", ... },
{ "useCaseId" : "1", ... },
{ "useCaseId" : "a", ... },
...
]
As you can see, the string begins with a [ character, like the exception demanded.
Since "most" jsons begin with { I'm guessing that your json structure is different, and then you'll be required to adjust your code accordingly. For example, if your json array is embedded in an object like "most" jsons are:
{
"useCases" : [
{ "useCaseId" : "4", ... },
{ "useCaseId" : "1", ... },
{ "useCaseId" : "a", ... },
...
]
}
then you would have to create a JSONObject obj = new JSONObject(jsonArrStr) and then get the JSONArray by calling (JSONArray)obj.get("useCases").

JSON get Array without object

I'm trying to parse this JSON,
{
"listname": "red",
"lists": [
{
"id": "01",
"name": "paw",
"list": [
{
"id": "A",
"name": "pawa",
"bar": "foo"
},
{
"id": "B",
"name": "pawb",
"bar": "foo"
}
]
},
{
"id": "02",
"name": "pew",
"list": [
{
"id": "A",
"name": "pewa",
"bar": "foo"
},
{
"id": "B",
"name": "pewb",
"bar": "foo"
}
]
},
{
"id": "03",
"name": "piw",
"list": [
{
"id": "A",
"name": "piwa",
"bar": "foo"
},
{
"id": "B",
"name": "piwb",
"bar": "foo"
}
]
}
]
}
I put it on Asset Folder and I read it and it converts it to me to String since here all good, the problem is when I'm trying to get the name from each item of lists and trying to get all the names from the list I've tried it doing this :
JSONObject obj = new JSONObject(str);
JSONArray jsonMainArr = obj.getJSONArray("lists"); //first get the lists
for (int i = 0; i < jsonMainArr.length(); i++) {
JSONObject childJSONObject = jsonMainArr.getJSONObject(i);
String name = childJSONObject.getString("name");
Toast.makeText(context, name, Toast.LENGTH_SHORT).show();
}
JSONObject obj = new JSONObject(str);
JSONArray jsonMainArr = obj.getJSONArray("list"); //get the list
for (int i = 0; i < jsonMainArr.length(); i++) {
JSONObject childJSONObject = jsonMainArr.getJSONObject(i);
String name = childJSONObject.getString("name");
Toast.makeText(context, name, Toast.LENGTH_SHORT).show();
}
But it doesn't show anything... what I'm missing?
EDIT
This is how I read the JSON
public static String loadJSONFromAsset(Context ctx, String str) {
String json = null;
try {
InputStream is = ctx.getAssets().open(str);
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
return json;
}
Since your "list" is nested in the childJSONObject (from "lists") , nest your for loops to retrieve the this set of values (the JSONobject)
JSONObject obj = new JSONObject(str);
//first get the top-level "lists"
JSONArray jsonMainArr = obj.getJSONArray("lists");
for (int i = 0; i < jsonMainArr.length(); i++) {
JSONObject childJSONObject = jsonMainArr.getJSONObject(i);
String name = childJSONObject.getString("name");
Toast.makeText(context, name, Toast.LENGTH_SHORT).show();
//get the inner "list" from childJSONObject
JSONArray childJSONArray = childJSONObject.getJSONArray("list");
for (int j = 0; j < childJSONArray.length(); j++) {
JSONObject childJSONObjectB = childJSONArray.getJSONObject(j);
String name = childJSONObjectB.getString("name");
Toast.makeText(context, name, Toast.LENGTH_SHORT).show();
}
}

Array inside JSONArray iteration in java

My Json is:
{
"Response": {
"Asset": [
{
"id": 2461,
"name": "TestAsset7771",
"model_name": "TestModel777",
"serial_number": "TestAsset7771",
"current_data": {
"timestamp": "",
"name": "Temperature",
"value": "?"
}
},
{
"id": 2448,
"model_id": 1229,
"name": "TestAsset777",
"model_name": "TestModel777",
"serial_number": "TestAsset777",
"current_data": {
"timestamp": "",
"name": "Temperature",
"value": "?"
}
}
]
}
}
My code is:
JSONObject outerObject = new JSONObject(jsonObj.toString());
JSONObject innerObject = outerObject.getJSONObject("Response");
JSONArray jsonArray = innerObject.getJSONArray("Asset");
for (int i = 0, size = jsonArray.length(); i < size; i++)
{
JSONObject objectInArray = jsonArray.getJSONObject(i);
String[] elementNames = JSONObject.getNames(objectInArray)
for (String elementName : elementNames)
{
String value = objectInArray.getString(elementName);
System.out.printf("name=%s, value=%s\n", elementName, value);
}
}
For inner array - ie current data, am getting values as:
name=current_data,
value={"timestamp":"","name":"Temperature","value":"?"}
How can i put another inner array so that i can get values of
"timestamp":"", "name":"Temperature", "value":"?" in separate variables instead of complete JSON
Its better to use Gson to parse JSON. Anyway, if you decide to follow as this is, try as :
You have a class like this:
class CurrentData{
String name,timestamp,value;
void print(){
System.out.printf("name=%s, timestamp=%s, value=%s\n", name,timestamp, value);
}
}
Now, change your for loop as follows:
for (String elementName : elementNames)
{
if(!elementName.equals("current_data")){
String value = objectInArray.getString(elementName);
System.out.printf("name=%s, value=%s\n", elementName, value);
}
else{
CurrentData obj=new CurrentData();// You can use array of objects declaring outside the loop as your need
JSONObject curr_object=objectInArray.getJSONObject("current_data");
obj.name=curr_object.getString("name");
obj.timestamp=curr_object.getString("timestamp");
obj.value=curr_object.getString("value");
obj.print();
}
}
for (String elementName : elementNames)
{
JSONObject jsonobject = jsonarray.getJSONObject(elementName);
System.out.printf( "name=%s, value=%s\n",jsonobject.getString("name"),jsonobject.getString("value"));
}
"value" is another jason object, so you can just call "getJasonObject()" to obtain the item and then proceed with that new array as normal.
Edit: I made a fail (not enough C0FFEE in my memory) and corrected thanks to the comment.
JSONObject outerObject = new JSONObject(jsonObj.toString());
JSONObject innerObject = outerObject.getJSONObject("Response");
JSONArray jsonArray = innerObject.getJSONArray("Asset");
for (int i = 0, size = jsonArray.length(); i < size; i++) {
JSONObject objectInArray = jsonArray.getJSONObject(i);
JSONObject currentData = objectInArray.getJSONObject("current_data");
if (currentData != null) {
String timestamp = currentData.getString("timestamp");
String name = currentData.getString("name");
String value = currentData.getString("value");
// Assign above results to array elements or whatever
}
}
//nested jsonarray
FileReader inp=new FileReader("xyz.json");
JSONParser parser=new JSONParser();
Object obj=parser.parse(inp);
JSONArray jsonArray=(JSONArray) obj;
int len=jsonArray.size();
for(i:len)
{
JSONArray json1=(JSONArray) jsonArray.get(i);
Iterato iterator=json1.iterator();
while(iterator.hasNext())
System.out.println(iterator.next());
}

How to remove JSONArray element using Java

My JsonArray is
[{
"Id": null,
"Name": "One New task",
"StartDate": "2010-02-03T05:30:00",
"EndDate": "2010-02-04T05:30:00",
"Duration": 1,
"DurationUnit": "d",
"PercentDone": 0,
"ManuallyScheduled": false,
"Priority": 1,
"parentId": 8,
"index": 0,
"depth": 3,
"checked": null },{
"Id": null,
"Name": "New task",
"StartDate": "2010-02-04T05:30:00",
"EndDate": "2010-02-04T05:30:00",
"Duration": 0,
"DurationUnit": "d",
"PercentDone": 0,
"ManuallyScheduled": false,
"Priority": 1,
"parentId": 8,
"index": 1,
"depth": 3,
"checked": null }]
Now from this JsonArray I want to remove Id, ManuallyScheduled, checked,
I tried using jsonArray.remove(1) and also jsonArray.discard("Id") in JAVA.
but nothing happens. what am I doing wrong to remove array items?
I am using JAVA as my technology.
What you have there is an array of objects. Therefore you'll have to loop through the array and remove the necessary data from each object, e.g.
for (int i = 0, len = jsonArr.length(); i < len; i++) {
JSONObject obj = jsonArr.getJSONObject(i);
// Do your removals
obj.remove("id");
// etc.
}
I've assumed you're using org.json.JSONObject and org.json.JSONArray here, but the principal remains the same whatever JSON processing library you're using.
If you wanted to convert something like [{"id":215},{"id":216}] to [215,216] you could so something like:
JSONArray intArr = new JSONArray();
for (int i = 0, len = objArr.length(); i < len; i++) {
intArr.put(objArr.getJSONObject(i).getInt("id"));
}
This is useful sometimes in android when you want to use the json structure directly.
Notice that I only use this when I'm handling JSONObject inside the array.
public static JSONArray remove(final int idx, final JSONArray from) {
final List<JSONObject> objs = asList(from);
objs.remove(idx);
final JSONArray ja = new JSONArray();
for (final JSONObject obj : objs) {
ja.put(obj);
}
return ja;
}
public static List<JSONObject> asList(final JSONArray ja) {
final int len = ja.length();
final ArrayList<JSONObject> result = new ArrayList<JSONObject>(len);
for (int i = 0; i < len; i++) {
final JSONObject obj = ja.optJSONObject(i);
if (obj != null) {
result.add(obj);
}
}
return result;
}
The following method will find the object in an array with the matching id, then return the filtered array.
public JSONArray removeObject(JSONArray array, String id) throws JSONException {
for (int i = 0; i < array.length(); i++) {
JSONObject obj = array.getJSONObject(i);
if (obj.getString("ID").equals(id)) {
array.remove(i);
// Toast.makeText(this, "ENCONTRADO", Toast.LENGTH_SHORT).show();
}
}
return array;
}

Categories

Resources