Alright. I have a JSON Object sent to me from a server which contains the following data:
{
"result":
[
{"status":"green","type":"data1"},
{"status":"green","type":"data2"},
{"status":"green","type":"data3"}
],
"status":"ok"
}
The data I want to get is the status for the three status values. Data1, data2, and data3 always show up in that order, so I'm now trying to grab the data by index (e.g. data1 = index 0, data2 = index 1, data3 = index 2). How do I do that?
Try following:
String stat1;
String stat2;
String stat3;
JSONObject ret; //contains the original response
//Parse to get the value
try {
stat1 = ret.getJSONArray("results").getJSONObject(0).getString("status");
stat2 = ret.getJSONArray("results").getJSONObject(1).getString("status");
stat3 = ret.getJSONArray("results").getJSONObject(2).getString("status");
} catch (JSONException e1) {
e1.printStackTrace();
}
You would use JSONObject and JSONArray, the entire string is one JSONObject so you would construct one with it.
JSONObject object = new JSONObject(YOUR_STRING_OF_JSON);
Then you can access it with different get methods depending upon your expected type.
JSONArray results = object.getJSONArray("result"); // This is the node name.
String status = object.getString("status");
for (int i = 0; i < results.length(); i++) {
String resultStatus = results.getJSONObject(i).getString("status");
String type = results.getJSONObject(i).getString("type");
Log.w("JSON Result #" + i, "Status: " + resultStatus + " Type: " + type);
}
You need to surround it with a try/catch because JSON access can throw a JSONException.
Try re-factoring via a forEach loop
var testData =
{
"result":
[
{"status":"green","type":"data1"},
{"status":"green","type":"data2"},
{"status":"green","type":"data3"}
],
"status":"ok"
};
var output = new Object;
var resultSet = new Object;
resultSet = testData.result;
resultSet.forEach(function(data)
{
theStatus = data['status'];
theType = data['type']
output[theType] = theStatus;
});
console.log( output['data1'] );
If you've got your models setup to mirror that data set, then you can let GSON (https://code.google.com/p/google-gson/) do a lot of your work for you.
If you want a bit more control, and want to parse the set yourself you can use JSONObject, JSONArray. There's an example of parsing and assembling a json string here: Android create a JSON array of JSON Objects
Related
I have a json data which can be something like:
1st json data
[
{
"id_form_delegate": "1",
"nama_merchant": "MATAHARI BARU SERASI",
"kota_merchant": "BALI",
"alamat_merchant": "JL PAKUBUWONO 2D",
"province_merchant": "BALI",
"mid_merchant": [
"112000902755",
"112000902754"
],
"tid_merchant": [
"2431002547",
"2531016215"
]
}
]
or something like
2nd json data
[
{
"id_form_delegate": "1",
"nama_merchant": "MATAHARI BARU SERASI",
"kota_merchant": "BALI",
"alamat_merchant": "JL PAKUBUWONO 2D",
"province_merchant": "BALI",
"mid_merchant": "112000902755",
"tid_merchant": "2431002547"
}
]
This my servlet code
JSONArray arrMid = jsonObject.getJSONArray("mid_merchant");
mid = new String[arrMid.size()];
JSONArray arrTid = jsonObject.getJSONArray("tid_merchant");
tid = new String[arrTid.size()];
//
System.out.println("nama_merchant: " + nama_merchant);
System.out.println("kota_merchant: " + kota_merchant);
System.out.println("alamat_merchant: " + alamat_merchant);
System.out.println("province_merchant: " + province_merchant);
System.out.println("mid: " + mid.length);
System.out.println("tid: " + tid.length);
if post 1st data result success, but if I post 2nd data I've Got error
this my error logs
net.sf.json.JSONException: JSONObject["mid_merchant"] is not a
JSONArray. net.sf.json.JSONException: JSONObject["tid_merchant"] is
not a JSONArray.
how to get value mid_merchant.length & tid_merchant.length using JSONArray
Thanks
The problem is that mid_merchant isn't an array in the second case, so you can't use JSONArray to get it's length because it has no length, it's just a String. You could send an array with only one value:
"mid_merchant": ["112000902755"],
or, if that's not what you want, you can check if it is an array (or even capture that exception) and get the String value with the getString method if it's not an array:
String stringMid = jsonObject.getString("mid_merchant");
You can use method get(String field) and check type of result:
Object node = jsonObject.get("mid_merchant");
String[] mid;
if (node instanceof JSONArray) {
mid = new String[((JSONArray) node).size()];
} else {
mid = new String[1];
}
or one-liner:
String[] mid = new String[node instanceof JSONArray ? ((JSONArray) node).size() : 1];
Try the following code
JSONArray arrMid=json.getJSONArray("mid_merchant");
String mid=arrMid.getJSONOBJECT.getJSONObject(0).getString("mid_merchant");
JSONArray tidMid=json.getJSONArray("tid_merchant");
String mid=tidMid.getJSONOBJECT.getJSONObject(0).getString("tid_merchant");
I want to parse an array from Server but I can't obtain the array
Here is the jsonString Successfully got :
{
"status":"OK",
"message":"this is your start and end coordinates",
"data":"{\"start\":[\"35.778763\",\"51.427360\"],\"end\":[\"35.768779, 51.415002\"]}"
}
I want the Double Values from data arraylist:
//try/catch
Log.d(TAG, "Passes here");
JSONObject jObject = new JSONObject(jsonString);
JSONArray jData = jObject.getJSONArray("data");
Log.d(TAG, "Not PAASING HERE !!! ");
JSONArray jArrayStart = (JSONArray) jData.get(0);
JSONArray jArrayEnd = (JSONArray) jData.get(1);
latitudeStart = (Double) jArrayStart.get(0);
longtitudeStart = (Double) jArrayEnd.get(1);
latitudeEnd = (Double) jArrayEnd.get(0);
longtitudeEnd = (Double) jArrayEnd.get(1);
What you're trying to parse, is a string.
{
"status": "OK",
"message": "this is your start and end coordinates",
"data": "{\"start\":[\"35.778763\",\"51.427360\"],\"end\":[\"35.768779, 51.415002\"]}"
}
So it works like this:
//first, retrieve the data from the response JSON Object from the server
JSONObject response = new JSONObject(jsonString);
String status = response.getString("status");
String message = response.getString("message");
//Note this: "data" is a string as well, but we'll have to parse that later.
String data = response.getString("data");
//get the doubles from the arrays from the "data" component.
JSONObject dataObject = new JSONObject(data);
JSONArray start = dataObject.getJSONArray("start");
JSONArray end = dataObject.getJSONArray("end");
for (int i = 0; i < start.length(); i++) {
String value = start.getString(i);
//do something with the start String (parse to double first)
}
for (int i = 0; i < end.length(); i++) {
String value = end.getString(i);
//do something with end String (parse to double first)
}
So data is actually a String, but represents a JSONObject (which you'll have to parse), which, in its turn, contains two JSONArrays.
If data was a JSONObject instead of a String, the JSON would have looked like this:
{
"status": "OK",
"message": "this is your start and end coordinates",
"data": {
"start": [
"35.778763",
"51.427360"
],
"end": [
"35.768779", //note that in your example, this quote is missing (first quote on next line too)
"51.415002"
]
}
}
The value of data is not a JSONArray its JSONObject
Explanation
JSONObject will be surrounded by {}
JSONArray will be surrounded by []
data is not an array, it is a json object and therefore you can not access it the way you are doing.
If you want to fetch start array from json object "data" then use below
jObject.optJSONObject("data").optJSONArray("start");
same thing can be used to retrieve "end" json array.
then use optJSONObject() and/or optString() API to retrieve required value from json array.
Trying to parse multi-level JSON in Java.
Having JSON input in format like this:
{"object1":["0","1", ..., "n"],
"objects2":{
"x1":{"name":"y1","type":"z1","values":[19,20,21,22,23,24]}
"x2":{"name":"y2","type":"z2","values":[19,20,21,22,23,24]}
"x3":{"name":"y3","type":"z1","values":[19,20,21,22,23,24]}
"x4":{"name":"y4","type":"z2","values":[19,20,21,22,23,24]}
}
and need to get all objects from 2 by one of the attributes, e.g. get all objects with type = z1.
Using org.json*.
Tried to do something like this:
JSONObject GeneralSettings = new JSONObject(sb.toString()); //receiving and converting JSON;
JSONObject GeneralObjects = GeneralSettings.getJSONObject("objects2");
JSONObject p2;
JSONArray ObjectsAll = new JSONArray();
ObjectsAll = GeneralObjects.toJSONArray(GeneralObjects.names());
for (int i=0; i < GeneralObjects.length(); i++){
p2 = ObjectsAll.getJSONObject(i);
switch (p2.getString("type")) {
case "z1": NewJSONArray1.put(p2); //JSON array that should contain values with type z1.
break;
case "z2": NewJSONArray2.put(p2); //JSON array that should contain values with type z2.
default: System.out.println("error");
break;
}
}
}
But getting null pointer exception and overall method seems not to be so well.
Please advise, is there any way to make it easier or, what am I doing wrong?
If you're getting a NullPointerException it's most likely that you haven't initialized NewJSONArray1 and NewJSONArray2.
You didn't include their declaration, but you probably just need to do
NewJSONArray1=new JSONArray();
NewJSONArray2=new JSONArray();
before your loop.
Aside: by convention java variables should start with a lower case letter, e.g. newJSONArray1
public static void main(String[] args) {
String s =
"{\"object1\":[\"0\",\"1\",\"n\"]," +
"\"objects2\":{" +
"\"x1\":{\"name\":\"y1\",\"type\":\"z1\",\"values\":[19,20,21,22,23,24]}," +
"\"x2\":{\"name\":\"y2\",\"type\":\"z2\",\"values\":[19,20,21,22,23,24]}," +
"\"x3\":{\"name\":\"y3\",\"type\":\"z1\",\"values\":[19,20,21,22,23,24]}," +
"\"x4\":{\"name\":\"y4\",\"type\":\"z2\",\"values\":[19,20,21,22,23,24]}" +
"}}";
System.out.println(s);
JSONObject json = new JSONObject(s);
JSONObject object2 = json.optJSONObject("objects2");
if (object2 == null) {
return;
}
JSONArray result = new JSONArray();
for (Object key : object2.keySet()) {
JSONObject object = object2.getJSONObject(key.toString());
String type = object.optString("type");
if ("z1".equals(type)) {
System.out.println(object.toString());
result.put(object);
}
}
System.out.println(result);
}
You can always convert it to string and use json-path:
https://code.google.com/p/json-path/
I expected to find this question around, but I couldn't. Maybe I'm Googling the wrong thing.
I have a primitive integer array (int[]), and I want to convert this into a String, that is "JSON-Parseable", to be converted back to the same int[].
What have I tried :
I tried this code :
// int[] image_ids_primitive = ...
JSONArray mJSONArray = new JSONArray(Arrays.asList(image_ids_primitive));
String jSONString = mJSONArray.toString();
Prefs.init(getApplicationContext());
Prefs.addStringProperty("active_project_image_ids", jSONString);
// Note: Prefs is a nice Class found in StackOverflow, that works properly.
When I printed the jSONString variable, it has the value : ["[I#40558d08"]
whereas, I expected a proper JSON String like this : {"1" : "424242" , "2":"434343"} not sure about the quotation marks, but you get the idea.
The reason I want to do this :
I want to keep track of local images (in drawable folder), so I store their id's in the int array, then I want to store this array, in the form of a JSON String, which will be later parsed by another activity. And I know I can achieve this with Intent extras. But I have to do it with SharedPreferences.
Thanks for any help!
You don't have to instantiate the JSONArray with Arrays.asList. It can take a normal primitive array.
Try JSONArray mJSONArray = new JSONArray(image_ids_primitive);
If you are using an API level below 19, one easy method would just be to loop over the int array and put them.
JSONArray mJSONArray = new JSONArray();
for(int value : image_ids_primitive)
{
mJSONArray.put(value);
}
Source: Android Developers doc
If you want a JSON array and not necessarily an object, you can use JSONArray.
Alternatively, for a quick hack:
System.out.println(java.util.Arrays.toString(new int[]{1,2,3,4,5,6,7}));
prints out
[1, 2, 3, 4, 5, 6, 7]
which is valid JSON. If you want anything more complicated than that, obviously JSONObject is your friend.
Try this way
int [] arr = {12131,234234,234234,234234,2342432};
JSONObject jsonObj = new JSONObject();
for (int i = 0; i < arr.length; i++) {
try {
jsonObj.put(""+(i+1), ""+arr[1]);
} catch (Exception e) {
}
}
System.out.println("JsonString : " + jsonObj.toString());
// If you wants the data in the format of array use JSONArray.
JSONArray jsonarray = new JSONArray();
//[1,2,1,] etc..
for (int i = 0; i < data.length; i++) {
jsonarray.put(data[i]);
}
System.out.println("Prints the Json Object data :"+jsonarray.toString());
JSONObject jsonObject=new JSONObject();
// If you want the data in key value pairs use json object.
// i.e {"1":"254"} etc..
for(int i=0;i<data.length;i++){
try {
jsonObject.put(""+i, data[i]);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("Prints the Json Object data :"+jsonObject.toString());
itertate this through the int array and you will get the json string
JSONStringer img = null ;
img = new JSONStringer() .object() .key("ObjectNAme")
.object() .key("something").value(yourIntarrayAtIndex0)
.key("something").value(yourIntarrayAtIndex1) .key("something").value(yourIntarrayAtIndex2)
.key("something").value(yourIntarrayAtIndex3)
.endObject() .endObject();
String se = img.toString();
Here se is your json string in string format
This code will achieve what you are after...
int index = 0;
final int[] array = { 100, 200, 203, 4578 };
final JSONObject jsonObject = new JSONObject();
try {
for (int i : array) {
jsonObject.put(String.valueOf(index), String.valueOf(i));
index++;
}
} catch (JSONException e) {
e.printStackTrace();
}
Log.d("YOUR_TAG", jsonObject.toString());
This will give you {"3" : "203", "2" : "200", "1": "100", "4": "4578"} as a string.
Not exactly sure why its not in the exact order, but sorting by a key is quite easy.
I have JSON code like this:
[{ "idShipping":"1328448569",
"shippingDesti":"nusa tenggara barat",
"shippingCosts":"21000"
},
{ "idShipping":"1328448543",
"shippingDesti":"nusa tenggara timur",
"shippingCosts":"76000"
}]
I followed a tutorial from this link: BlackBerry read json string from an URL. I changed
private static final String NAME = "name";
from DataParser.java into
private static final String NAME = "idShipping";
but when i run it on a simulator, it showed a popup screen that said that it failed to parse data from MyScreen.java. It means I can get the JSON string, but I can't parse it.
How do I fix it?
For the JSON you've shown, you would parse the idShipping values something like this:
//String response = "[{\"idShipping\":\"1328448569\",\"shippingDesti\":\"nusa tenggara barat\",\"shippingCosts\":\"21000\"},{\"idShipping\":\"1328448543\",\"shippingDesti\":\"nusa tenggara timur\",\"shippingCosts\":\"76000\"}]";
try {
JSONArray responseArray = new JSONArray(response);
for (int i = 0; i < responseArray.length(); i++) {
JSONObject nextObject = responseArray.getJSONObject(i);
if (nextObject.has("idShipping")) {
String value = nextObject.getString("idShipping");
System.out.println("next id is " + value);
}
}
} catch (JSONException e) {
// TODO: handle parsing error here
}
The key, as Signare said, was parsing a JSONArray, and then getting a string value out of that.