Parse 2d Json in java [duplicate] - java

This question already has answers here:
How to parse JSON 2D array using Java
(2 answers)
How do I parse JSON in Android? [duplicate]
(3 answers)
Closed 5 years ago.
Trying to parse this type of json format in java
{
"output": "success",
"result": [
{
"id": 1,
"label": "name",
},
{
"id": 2,
"label": "name_2",
}
]
}
I am getting this type of json format, now what i want to do is check first if output.equalsIgnoreCase("success)" if true then parse the second array of result.
And this is i tried so far.
try {
JSONArray myJson = new JSONArray(response);
String status = myJson.getString(Integer.parseInt("output"));
if(status.equalsIgnoreCase("success")) {
for (int i = 0; i < myJson.length(); i++) {
JSONObject obj = myJson.getJSONObject(i);
name.add(obj.getString("label"));
}
Log.e("list" , name.toString());
}
} catch (Exception e) {
}

String responceStr = ...; // here is your full responce string
try {
JSONObject responce = new JSONObject(responceStr);
String status = responce.getString("output");
if ("success".equalsIgnoreCase(status)) {
JSONArray result = responce.getJSONArray("result");
for (int i=0; i < result.length(); i++){
JSONObject jsonPair = result.getJSONObject(i);
int id = jsonPair.getInt("id");
String label = jsonPair.getString("label");
}
}
} catch (JSONException e){
}
Integer.parseInt("123") -- is OK.
Integer.parseInt("output") -- is NOT OK.
because Integer.parseInt() parses the string representation of an integer. "output" string does not represent an integer.

The response is a JSONObject, not JSONArray (it is enclosed between curly brackets). The array is the field named result.
So change myJson to JSONObject and after checking the success field,
create a new variable
JSONArray resultArray = myJson.getArray("result");
and iterate over this instead of myJson. Also you should not discard the exception since the stacktrace could provide some hint about the problems. You can add
e.printStackTrace();
in the catch block.

Related

(SOLVED) How to parse this json nested array [duplicate]

This question already has answers here:
How to parse JSON in Java
(36 answers)
Closed 2 years ago.
I got stuck in parsing this JSON, I has read a some references in GitHub or google and not same for this case, can anyone give me guided or references
{
"index":
{
"data":[
{
"id":1,
"name":"John",
"room":31
}
]
}
}
EDIT: we has found a more simple json format
The solve by me
{
"data":[
{
"id":1,
"name":"John",
"room":31
}
]
}
try {
JSONObject jsonArray = new JSONObject(response);
JSONArray list = jsonArray.getJSONArray("data");
for (int i = 0; i <list.length(); i++) {
String id= list.getJSONObject(i).getString("id");
String name = list.getJSONObject(i).getString("name");
String room= list.getJSONObject(i).getString("room");
KItem KTItem = new KasusItem(id,name,room);
kItemList.add(KTItem);
}
JSONArray data = JSONObject(response).getJSONObject("index).getJSONArray("data);
for(int i=0; i<data.length; i++){
JSONObject obj = data.getJSONObject(i);
String id = obj.getString("id");
String name = obj.getString("name");
}

How to store JSON response in an array list? [duplicate]

This question already has answers here:
Converting JSONarray to ArrayList
(23 answers)
Closed 8 years ago.
I want to store a JSON response in array list so that it will be easy to fetch data and assign it to other variables.
This is my JSON response:
{
"statusCode":"1001",
"message":"Success",
"response":{
"holidays":[
{
"holidayId":78,
"year":2015,
"date":"2015-01-01",
"day":"Thrusday",
"occasion":"New Year Day",
},
{
"holidayId":79,
"year":2015,
"date":"2015-01-15",
"day":"Thrusday",
"occasion":"Pongal/Sankranthi",
},
{
"holidayId":80,
"year":2015,
"date":"2015-01-26",
"day":"Monday",
"occasion":"Republic Day",
}
],
"year":0
}
}
This is the way I am fetching data from the response:
JSONObject jobj = new JSONObject(result);
String statusCode = jobj.getString("statusCode");
if (statusCode.equalsIgnoreCase("1001"))
{
System.out.println("SUCCESS!");
String response = jobj.getString("response");
JSONObject obj = new JSONObject(response);
String holidays = obj.getString("holidays");
ArrayList<HolidayResponse> holidayResponse = holidays; //This stmt. shows me error
}
How do I solve this issue? Please help me.
that is because of a JSON parse exception:
the holidays is a JSON array.Hence the correct way would be:
JSONObject obj = new JSONObject(response);
JSONArray holidays = obj.getJSONArray("holidays");
look here to convert that to array list.
Instead of all this hassle,you could use Gson or Jackson

how to reverse the json array after response from webservice?

I am getting response this
{
"success": 1,
"message": "some message",
"data": [
{
"comment_id": "43906",
"comp_id": "116725",
"user_id": "48322",
"agree": "0",
.....
"replies": [....]
},
{
"comment_id": "43905",
"comp_id": "116725",
"user_id": "48248",
"agree": "0",
.......
"replies": [...]
}
]
}
I am to get all response in json array like this
JSONObject js =new JSONObject(response);
routeJsonArray.=js.getJSONArray("data");
But I need to reverse all object which is inside data array .In other word when I get response and print commant_id "43906", "43905",
But I need I reverse that objects so that when I print it first give "43905","43906",
there is solution to iterate from i = routeJsonArray.length; i > 0; i-- But i don't want this.I want to store reverse array in another array ..
I try like this.
String [] routeStationString;
JSONArray localJsonArray = js.getJSONArray("data");
routeStationString = new String[localJsonArray.length()];
int k = 0;
for (int i = localJsonArray.length(); i > 0; i--) {
routeStationString[k++] = localJsonArray.getJSONObject(i);
}
System.out.println(routeStationString);
It gives error.?
My approach would be to create a Java Model representing a comment from your array and then proceed like this.
ArrayList<Comment> mList = new ArrayList<Comment>();
for(int i=0;i<routeJsonArray.length();i++){
//get the jsonobject based on the position
//retrieve its values
//create a new comment object and store it to the mList
}
Collection.reverse(mList);
You typically want to parse this array into a POJO, a model. So the idea would be to get a List<Comment> list for example and then you would be able to reverse that list through Collections.reverse(list) method.
How do you use the data from the JSON array? you still have to iterate it, plus remember the keys and everything. the most typical solution is to parse the JSON data into java objects.
JSONArray toReturn = new JSONArray();
int length = jsonArray.length()-1;
for(int i =length; i >= length;i--){
try {
toReturn.put(jsonArray.getJSONObject(i));
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(this, "Something wrong", Toast.LENGTH_SHORT).show();
}
}

parse json array in android

I need a help... I have a php file which returns me two json Arrays which are as follows:
[{ "id":"1",
"item":"hammers",
"aisle":"20"
}
{ "id":"1",
"item":"hammers",
"aisle":"20"
}]
[{ "id":"1",
"itemFound":"Your item #item",
"ThankYou":"and Thank You for using Txtcore!"
}]
Now, I want to get the second array items in Android. I have the following code now which is like :
JSONArray jsonArray = new JSONArray(result);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
items.add(jsonObject.getString("item"));
aisles.add(""+jsonObject.getString("item");
}
But obviously, that returns me the objects from the first array. I want to get the Objects from the second array. Any suggestions.
Your JSON is not valid but u can get your element as follows. It is a solution from many(just a worlaround).
String str = "YOUR_JSON_RESPONSE";
String array[] = str.split("\\[\\{");//
try {
JSONArray jsonArray=new JSONArray("[{" + array[2]));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
I guess you'll have to do some dirty coding because the data return by the PHP page is not well formed JSON.
You could try to transform the JSON data to:
{ "data" : [ <array_1>, <array_2> ]} And then use the JSON parser. A simple replacement with a regexp could be fine.
result.replaceAll("\\]\\s*\\[", "], [");
StringBuffer buffer=new StringBuffer(result);
buffer.insert(0,"{ \"data\": ");
buffer.append(" }");
JSONObject jsonObject = new JSONObject(buffer.toString());
JSONArray secondArray= jsonObject.getJSONArray("data").getJSONArray(1);
The creation of a valid JSON string can be done in one step with the appropriate regexp. Hope some one with more time can post it here.

How to convert int Array to JSON String in Android?

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.

Categories

Resources