How to parse specific JSON data in Android? - android

This is my JSON data from a URL:
[
{ "title" : "65th Issue", "author": "అశోక్"},
{ "title" : "64th Issue", "author": "రాము" },
{ "title" : "63rd Issue", "author": "శ్రీను" }
]
It is looking like a JSONArray but it does not have its name (Array name) to access. Could anyone tell me how can I parse this JSON data in android?
Parsing Code
InputStream inputStream = connection.getInputStream();
Reader reader = new InputStreamReader(inputStream);
int contentLength = connection.getContentLength();
char [] charArray = new char[contentLength];
reader.read(charArray);
String responseData = new String(charArray);
try{
JSONArray jArray = new JSONArray(responseData);
for(int i = 0; i < jArray.length(); i++) {
String title = jArray.getJSONObject(i).getString("title");
}
} catch (JSONException e) {
Log.v(TAG, "JSON EXCEPTION");
}

String jsonString = ...; //This contains the above mentioned String.
For JSON String, [] denotes an array, an {} denotes an object. In your case, the string starts with a [] thats means its an array, so we first get the JSONArray.
JSONArray jArray = new JSONArray(jsonString);
Now, if you see, the array has multiple strings beginning and ending with {}, that means that the array has multiple objects. So we run a loop over the array length to extract each object and then the key - value from the object.
for(int i = 0; i < jArray.length(); i++) {
String title = jArray.getJSONObject(i).getString("title");
}
So, the complete code will be something like this :
String jsonString = ...; //This contains the above mentioned String.
JSONArray jArray = new JSONArray(jsonString);
for(int i = 0; i < jArray.length(); i++) {
String title = jArray.getJSONObject(i).getString("title");
}
Edit 2 :
String jsonString = "[\r\n { \"title\" : \"65th Issue\", \"author\": \"\u0C05\u0C36\u0C4B\u0C15\u0C4D\"},\r\n { \"title\" : \"64th Issue\", \"author\": \"\u0C30\u0C3E\u0C2E\u0C41\" },\r\n { \"title\" : \"63rd Issue\", \"author\": \"\u0C36\u0C4D\u0C30\u0C40\u0C28\u0C41\" }\r\n]";
try {
JSONArray jArray = new JSONArray(jsonString);
for (int i = 0; i < jArray.length(); i++) {
String title = jArray.getJSONObject(i).getString("title");
Log.d(LOGTAG, title);
}
} catch (JSONException e) {
e.printStackTrace();
}

Related

nested JSON object inside JSON array

I'm trying to parse a JSON object. The JSON response is as follows.
{
"message": "Success",
"list": [
{
"orderId": 24,
"phoneNumber": "1234567893",
"totalAmount": 100,
"addressBean": {
"cadId": 1,
"phone2": "1234567899",
"address1": "34, gandhi nagar",
}
},
Android code which i have tried for getting "orderId", "phoneNumber" and "totalAmount" is below.
final List<OrderModel> orderList = new ArrayList<>();
public void onResponse(JSONObject response) {
try {
if (response.getString("message").equalsIgnoreCase("Success")) {
JSONArray jArray = response.getJSONArray("list");
for (int i = 0; i < jArray.length(); i++) {
OrderModel model = new OrderModel();
orderModel.setOrderId(jArray.getJSONObject(i).getString("orderId"));
orderModel.setphoneNumber(jArray.getJSONObject(i).getString("phoneNumber"));
orderModel.setTotalAmount(new BigDecimal(jArray.getJSONObject(i).getString("totalAmount")));
orderList.add(orderModel);
}
setOrderList(orderList);
I want to show the "cadId", "phone2" and "address1" in a Textview. How can i do that?
Try to use this Code
try {
JSONArray jArray = response.getJSONArray("list");
for (int i = 0; i < jArray.length(); i++) {
JSONObject jsonObject = jArray.getJSONObject(i);
if (jsonObject.has("addressBean")){
JSONObject addressObject = jsonObject.getJSONObject("addressBean");
int cadId = addressObject.getInt("cadId");
String phone = addressObject.getString("phone2");
String address = addressObject.getString("address1");
}
}
} catch (JSONException e) {
e.printStackTrace();
}
Code for phone2
String phone2 = jArray.getJSONObject(i).getJSONObject("addressBean").getString("phone2");
Use getInt() for cadId

Android : parse a JSONArray

I would need help to parse this JSONArray in my Android app. I'm a bit confused with JSONObjects and JSONArrays :
[
{
"nid": [
{
"value": "3"
}
],
"uid": [
{
"target_id": "1",
"url": "/user/1"
}
],
"field_image": [
{
"target_id": "2",
"alt": "alternate 1",
"title": "",
"width": "640",
"height": "640",
"url": "http://url"
},
{
"target_id": "3",
"alt": "alternate 2",
"title": "",
"width": "640",
"height": "640",
"url": "http://url"
}
]
}]
Here is what I've got to start the iteration :
public void onResponse(JSONArray response) {
try {
jsonResponse = "";
for (int i = 0; i < response.length(); i++) {
...
Here is your code to parse data,
private void parseData(){
try {
JSONArray jsonArray=new JSONArray(response);
JSONObject jsonObject=jsonArray.getJSONObject(0);
JSONArray jsonArrayNid=jsonObject.getJSONArray("nid");
JSONArray jsonArrayUid=jsonObject.getJSONArray("uid");
JSONArray jsonArrayField_image=jsonObject.getJSONArray("field_image");
for(int i=0;i<jsonArrayNid.length();i++){
JSONObject jsonObjectNid=jsonArrayNid.getJSONObject(i);
String value=jsonObjectNid.getString("value"); //here you get your nid value
}
for(int i=0;i<jsonArrayUid.length();i++){
JSONObject jsonObjectUid=jsonArrayUid.getJSONObject(i);
String target_id=jsonObjectUid.getString("target_id"); //here you get your uid target_id value
String url=jsonObjectUid.getString("url"); //here you get your uid url value
}
for(int i=0;i<jsonArrayField_image.length();i++){
JSONObject jsonObjectFieldImage=jsonArrayField_image.getJSONObject(i);
String target_id=jsonObjectFieldImage.getString("target_id");
String alt=jsonObjectFieldImage.getString("alt");
String title=jsonObjectFieldImage.getString("title");
String width=jsonObjectFieldImage.getString("width");
String height=jsonObjectFieldImage.getString("height");
String url=jsonObjectFieldImage.getString("url");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
for (int i = 0; i < response.length(); i++) {
JSONObject tobject = response.getJSONObject(i);
JSONArray nid = tobject.getJSONArray("nid");
JSONArray uid= tobject.getJSONArray("uid");
JSONArray field_image= tobject.getJSONArray("field_image");
//similarly you can loop inner jsonarrays
}
Use code according to you:
JSONArray array = null;
try {
array = new JSONArray(url); // your web url
JSONObject object = array.getJSONObject(0);
JSONArray array1 = object.getJSONArray("nid");
JSONObject object1 = array1.getJSONObject(0);
String value = object1.getString("value");
JSONArray array2 = object.getJSONArray("uid");
JSONObject object2 = array2.getJSONObject(0);
String target = object2.getString("target_id");
String url = object2.getString("url");
JSONArray array3 = object.getJSONArray("field_image");
JSONObject object3 = array3.getJSONObject(0);
String alt = object3.getString("alt");
Toast.makeText(Testing.this,value+"\n"+target+"\n"+url+"\n"+alt,Toast.LENGTH_LONG).show();
} catch (JSONException e) {
e.printStackTrace();
}
Try to parse like this.
In this code, jsonArray is the parent array which you have in your JSON.
for(int i=0;i<jsonArray.length();i++)
{
try {
JSONObject object=jsonArray.getJSONObject(i);
JSONArray imageArray=object.getJSONArray("field_image");
for(int j=0;j<imageArray.length();j++)
{
JSONObject imageObject=imageArray.getJSONObject(j);
String targetId=imageObject.getString("target_id");
}
}
catch (JSONException e) {
e.printStackTrace();
}
}
Now :) if you have to parse something first look for some library:
http://www.java2s.com/Code/Jar/g/Downloadgson222jar.htm
Download gson.jar and then create java classes that mimic your desired json:
class C1{
private String value;
}
class C2{
private String target_id;
private String url;
}
class C3{
private String target_id;
private String alt;
private String title;
private String width;
private String height;
private String url;
}
class c4{
private List<C1> nid;
private List<C2> uid;
private List<C3> field_image;
}
Since you receive array from C4, you parse it like this:
public void onResponse(JSONArray response){
String value = response.toString();
GsonBuilder gb = new GsonBuilder();
Type arrayType = new TypeToken<List<C4>>() {}.getType();
List<C4> data = gb.create().fromJson(value, arrayType);
}
So in just 3 lines of code, you have your entire json serialized to java objects that you can use in your code.
Try
public void onResponse(JSONArray response) {
try {
if (response != null) {
for (int i = 0; i < response.length(); i++) {
JSONObject jsonObject = resultsArray.getAsJsonObject(i);
//get nid array
JSONArray nidJSONArray = jsonObject.getJSONArray("nid");
//get uid array
JSONArray uidJSONArray = jsonObject.getJSONArray("uid");
//get field_image array
JSONArray fieldImageJSONArray = jsonObject.getJSONArray("field_image");
//parse nid array
if (nidJSONArray != null) {
for (int i = 0; i < nidJSONArray.length(); i++) {
JSONObject jsonObject = nidJSONArray.getAsJsonObject(i);
String value = jsonObject.getString("value");
}
}
//parse uid array
if (uidJSONArray != null) {
for (int i = 0; i < uidJSONArray.length(); i++) {
JSONObject jsonObject = uidJSONArray.getAsJsonObject(i);
String targetId = jsonObject.getString("target_id");
String url = jsonObject.getString("url");
}
}
//parse field_image array
if (fieldImageJSONArray != null) {
for (int i = 0; i < fieldImageJSONArray.length(); i++) {
JSONObject jsonObject = fieldImageJSONArray.getAsJsonObject(i);
String targetId = jsonObject.getString("target_id");
String alt = jsonObject.getString("alt");
String title = jsonObject.getString("title");
String width = jsonObject.getString("width");
String height = jsonObject.getString("height");
String url = jsonObject.getString("url");
}
}
}
}
} catch(Exception e) {
Log.e("Error", e.getMessage());
}
}

Json Parse android

Hi guys i got a json string like
{
"Successful": true,
"Value": "{\"MesajTipi\":1,\"Mesaj\":\"{\\\"Yeni\\\":\\\"Hayır\\\",\\\"Oid\\\":\\\"3d9b81c9-b7b3-4316-8a73-ad4d54ee02a8\\\",\\\"OzelKod\\\":\\\"\\\",\\\"Adet\\\":1,\\\"ProblemTanimi\\\":\\\"999\\\",\\\"HataTespitYeri\\\":\\\"Montajda\\\",\\\"Tekrar\\\":\\\"Evet\\\",\\\"ResmiBildirimNo\\\":\\\"\\\",\\\"Malzeme\\\":\\\"5475ffdb-0bc0-49cb-9186-429c60dbf91b\\\",\\\"HataKodu\\\":\\\"c30df623-496b-4a62-ba16-493bd435ca33\\\",\\\"Tarih\\\":\\\"2016-04-16 10:34:00\\\",\\\"KayitNo\\\":\\\"1600010.2\\\"}\"}"
}
I need to get "Oid" value from this string.
I tried to get it with
Gson gson = new Gson();
JsonParser parse = new JsonParser();
JsonObject jsonobj = (JsonObject) parse.parse(snc);
String stroid = jsonobj.get("Oid").toString();
But it gives null referance exception ? Any idea how can i get the only Oid value ?
Edit
I already tried How to parse JSON in Java but still no succes
What i tried from this page :
String pageName = jsonObj.getJSONObject("Value").getJSONObject("Mesaj").getString("Oid");
lets say this is your JSON
{
"success":"ok",
"test" : [{"id" : "1" ,"name" : "first"}]
,"RPTF":
[{"cats":[{"id" : "1" ,"name" : "first"},
{"id" : "1" ,"name" : "first"},
{"id" : "2" ,"name" : "test"} ]
,"pics" : [{"id" : "12" ,"value" : "description" ,"src" : "http://citygram.ir" ,"visit" : "3" },
{"id" : "10" ,"value" : "description" ,"src" : "http://citygram.ir" ,"visit" : "3" } ]
}]
}
method number one (if you want to access "success")
public String jsonOne(String json, String target) {
String result;
try {
JSONObject jo = new JSONObject(json);
result = jo.getString(target);
} catch (JSONException e) {
return "";
}
return result;
}
you can simply call this method like this
jsonOne(String json, "success");
method number two (in case you want to access "id"s inside the "test")
public String[] jsonTwo(String json, String target0, String target1) {
String[] result;
result = new String[1];
try {
JSONObject jo = new JSONObject(json);
JSONArray ja = jo.getJSONArray(target0);
result = new String[ja.length()];
for (int i = 0; i < ja.length(); i++) {
JSONObject jojo = ja.getJSONObject(i);
result[i] = jojo.getString(target1);
}
} catch (JSONException e) {
}
return result;
}
you get an array String on call :
jsonTwo(String json, "test", "id");
method number three (let's say you want to access "value"s in side "pics")
public String[] jsonThree(String json, String target0, String target1,String target2) {
String[] result;
result = new String[1];
try {
JSONObject jo = new JSONObject(json);
JSONArray ja = jo.getJSONArray(target0);
JSONObject jojo=ja.getJSONObject(0);
JSONArray jaja=jojo.getJSONArray(target1);
result = new String[jaja.length()];
for (int i = 0; i < ja.length(); i++) {
JSONObject jojojo = jaja.getJSONObject(i);
result[i] = jojojo.getString(target2);
}
} catch (JSONException e) {
toast("Wrong");
}
return result;
}
on call :
jsonThree(String json, "RPTF", "pics", "value");
you can write more methods like this and just call them .
The problem is because of extra " " in the "Value" section of JSON, so it will be treated as String not an object. The better solution is to seek the source of the JSON to see why they added extra " " and clear that but if you don't have access the source I propose the following:
Replace:
String stroid = jsonobj.get("Oid").toString();
with:
String valueString = jsonobj.getString("Value");
jsonobj = new JSONObject(valueString);
String mesagString = jsonobj.getString("Mesaj");
jsonobj = new JSONObject(mesagString);
String stroid = jsonobj.getInt("Oid").toString();

JSON array not being parsed [duplicate]

This question already has an answer here:
JSON array parsing in android
(1 answer)
Closed 7 years ago.
I have a JSON response in this format:
{
"success": true,
"categories": [{
"id": "774",
"name": "1"
}, {
"id": "774",
"name": "1"
}]
}
And I am parsing it like this:
try {
JSONObject obj = new JSONObject(response);
String success = String.valueOf(obj.getBoolean("success"));
JSONArray arr = obj.getJSONArray("categories");
//loop through each object
for (int i=0; i<arr.length(); i++) {
JSONObject jsonProductObject = arr.getJSONObject(i);
String name = jsonProductObject.getString("name");
String url = jsonProductObject.getString("id");
Toast.makeText(getApplicationContext(),name, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
But I only get the value of success. What I'm doing wrong here?
Parse as below -
JSONObject obj = new JSONObject(json);
String success = obj.getString("success");
JSONArray arr = obj.getJSONArray("categories");
//loop through each object
for (int i=0; i<arr.length(); i++) {
JSONObject jsonProductObject = arr.getJSONObject(i);
String name = jsonProductObject.getString("name");
String url = jsonProductObject.getString("id");
}
correct json key
JSONArray arr = obj.getJSONArray("checkouts");
replace by:
JSONArray arr = obj.getJSONArray("categories");
DO like this,
if (!result.equalsIgnoreCase("")) {
try {
JSONObject _jsonObject = new JSONObject(result);
boolean json = false;
json = _jsonObject.getBoolean("Status");
JSONArray jsonArray1 = _jsonObject.getJSONArray("categories");
for (int i=0; i<jsonArray1.length(); i++) {
JSONObject jsonObject = jsonArray1.getJSONObject(i);
String name = jsonObject.getString("name");
String id = jsonObject.getString("id");
}
} catch (Exception e) {
Utils.printLoge(5, "error parse json", "--->" + e.getMessage());
return "ERROR";
}
}

How do I pull the string array from this json object?

I am trying to get a list of available numbers from the following json object, using the class from org.json
{
"response":true,
"state":1,
"data":
{
"CALLERID":"81101099",
"numbers":
[
"21344111","21772917",
"28511113","29274472",
"29843999","29845591",
"30870001","30870089",
"30870090","30870091"
]
}
}
My first steps were, after receiving the json object from the web service:
jsonObj = new JSONObject(response);
jsonData = jsonObj.optJSONObject("data");
Now, how do I save the string array of numbers?
use:
jsonObj = new JSONObject(response);
jsonData = jsonObj.optJSONObject("data");
JSONArray arrJson = jsonData.getJSONArray("numbers");
String[] arr = new String[arrJson.length()];
for(int i = 0; i < arrJson.length(); i++)
arr[i] = arrJson.getString(i);
you need to use JSONArray to pull data in an array
JSONObject jObj= new JSONObject(your_json_response);
JSONArray array = jObj.getJSONArray("data");
Assuming that you are trying to get it in a javascript block, Try something like this
var arrNumber = jsonData.numbers;
My code is for getting "data":
public void jsonParserArray(String json) {
String [] resultsNumbers = new String[100];
try {
JSONObject jsonObjectGetData = new JSONObject(json);
JSONObject jsonObjectGetNumbers = jsonObjectGetData.optJSONObject("results");
JSONArray jsonArray = jsonObjectGetNumbers.getJSONArray("numbers");
for (int i = 0; i < jsonArray.length(); i++) {
resultsNumbers[i] = jsonArray.getString(i);
}
} catch (JSONException e) {
e.printStackTrace();
Log.e(LOG_TAG, e.toString());
}
}

Categories

Resources