Json Parsing object inside Object getting error - android

-- I know parsing, i have successfully parsed below data, but when web-service is upgraded i need to parse object inside object.
- I tried many example but getting error.
Code for Parsing :
private final String KEY_SUCCESS = "status";
private final String KEY_MSG = "Message";
private final String KEY_MSG1 = "Message";
// private final String KEY_AddressList = "addressList";
private final String KEY_USERINFO = "user_info";
ArrayList<HashMap<String, String>> arraylist;
private final String KEY_DATA = "data";
private final String KEY_USERDATA = "userdata";
public ArrayList<HashMap<String, String>> getList(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
if (jsonObject.getString(KEY_SUCCESS).equals("true")) {
arraylist = new ArrayList<HashMap<String, String>>();
JSONArray jsonArray = jsonObject.getJSONArray("data");
for (int i = 0; i < jsonArray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
JSONObject obj = jsonArray.getJSONObject(i);
// JSONObject job = obj.getJSONObject("User");
Log.d("obj", obj.toString());
String user_id = obj.getString(Constants.Params.ID);
String createdate = obj.getStringAndyConstants.Params.CREATEDDATE);
String postImage = obj.getString(Constants.Params.IMAGE);
map.put(AndyConstants.Params.ID, user_id);
map.put(AndyConstants.Params.CREATEDDATE, createdate);
map.put(AndyConstants.Params.IMAGE, postImage);
JSONObject objectDetails2 = obj.getJSONObject(KEY_DATA);
JSONArray jsonArrayUser = objectDetails2.getJSONArray("userdata");
for (int j = 0; j < jsonArrayUser.length(); j++) {
HashMap<String, String> mapUser = new HashMap<String, String>();
JSONObject businessObject = jsonArrayUser.getJSONObject(j);
Log.d("obj", businessObject.toString());
}
Log.d("map", map.toString());
arraylist.add(map);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return arraylist;
}
Error Log :
org.json.JSONException: No value for data
E/array: []
E/adapter: []
Json :
{
"status": true,
"message": "Successfully add Post",
"data": [{
"user_id": "46",
"image": "",
"createdate": "2016-05-11 06:05:12",
"userdata": {
"first_name": "Alpha",
"last_name": "Gamma",
"image": "http:\/\/abcd.net\/abcd\/uploads\/100520161005191462941615032.jpg"
}
}

You dont need this line
JSONObject objectDetails2 = obj.getJSONObject(KEY_DATA);
and change
JSONArray jsonArrayUser = objectDetails2.getJSONArray("userdata");
to
JSONObject userData = obj.getJSONObject("userdata");
String firstName = userData.getString("first_name");
String lastName = userData.getString("last_name");
As you can see from the JSON
"data":
[{"user_id":"46",
"image":"",
"createdate":"2016-05-11 06:05:12",
"userdata":{"first_name
data is having the object [ which denotes an Array while userData shows a { which is a JSONObject

I notice that your JSON has some errors. is this the complete Json response?
Because JSON response should be something like this:
{
"status": true,
"message": "Successfully add Post",
"data": [{
"user_id": "46",
"image": "",
"createdate": "2016-05-11 06:05:12",
"userdata": {
"first_name": "Alpha",
"last_name": "Gamma",
"image": "http:\/\/abcd.net\/abcd\/uploads\/100520161005191462941615032.jpg"
}
}]
}
You will notice that there is no close for [ after userdata in your Json.

Related

How to parse a JSON string in Android?

The following JSON string comes to me after a request. Whatever I try, I can not parse the data.
[{
"_id": {
"$oid": "5909846cbd966f2d371bc624"
},
"member_id": "NTkwOTEyNzdiZDk2NmYyZDM3MTkyY2M1",
"sensor_name": "Temprature",
"value": "27.28",
"date": "2017-05-03 10:19:07"
}]
Try using following code :
try {
JSONArray jsonArray = new JSONArray(response);
JSONObject jsonObject = jsonArray.get(0);
JSONObject _id = jsonObject.getJSONObject("_id");
String old = _id.getString("$oid");
String member_id = jsonObject.getString("member_id");
String sensor_name = jsonObject.getString("sensor_name");
String value = jsonObject.getString("value");
String date = jsonObject.getString("date");
}catch(JSONException e){
}

Getting JSON Array values Within a JSOn Object and Use In Class Object

I am trying to populate a class object with JSON data, and I keep getting this error
org.json.JSONException: No value for machinereports
Here is the sample json file, I am trying to use
{
"id" : 1,
"reports": [
{
"id": "1",
"title": "For Reorder",
"subtitle": "Report Name",
"date": "Monday, Aug 08, 2016",
"machinereports": [
{
"name": "Reorder List",
"count": "9"
},
{
"name": "Reorder List Critical",
"count": "9"
}
]
}
]
}
Here is the code I am trying to retrieve and populate my class object with
public class Report {
public String id;
public String title;
public String subtitle;
public String date;
public ArrayList<String> machinereports = new ArrayList<>();
public static ArrayList<Report> getReportsFromFile(String filename, Context context) {
final ArrayList<Report> reportList = new ArrayList<>();
try {
// Load Data
String jsonStr = loadJsonFromAsset("reports.json", context);
JSONObject jsonOne = new JSONObject(jsonStr);
JSONArray reports = jsonOne.getJSONArray("reports");
// Get Report objects from data
for(int i = 0; i < reports.length(); i++) {
Report report = new Report();
report.id = reports.getJSONObject(i).getString("id");
report.title = reports.getJSONObject(i).getString("title");
report.subtitle = reports.getJSONObject(i).getString("subtitle");
report.date = reports.getJSONObject(i).getString("date");
// Get inner array listOrReports
JSONArray rList = jsonOne.getJSONArray("machinereports");
for(int j = 0; j < rList.length(); j++) {
JSONObject jsonTwo = rList.getJSONObject(j);
report.machinereports.add(jsonTwo.getString("reportName"));
/* report.machinereports.add(jsonTwo.getString("count"));*/
}
reportList.add(report);
}
} catch (JSONException e) {
e.printStackTrace();
}
return reportList;
}
I can't seem to figure out, where I am having the problem, when I step through, when it gets to second JSONArray object it goes to the catch exception.
Your JSON does not have a field named reportName.
report.machinereports.add(jsonTwo.getString("reportName"));
change it to
report.machinereports.add(jsonTwo.getString("name"));
Also with the answer from #comeback4you you have the wrong call to the JsonArray.
JSONArray rList = jsonOne.getJSONArray("machinereports");
Should be
JSONArray rList = reports.getJSONObject(i).getJSONArray("machinereports");
JSONArray rList = jsonOne.getJSONArray("machinereports");
change to
JSONArray rList = reports.getJSONObject(i).getJSONArray("machinereports");
and inside for loop change below
report.machinereports.add(jsonTwo.getString("name"));

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());
}
}

how to get the json respose in two json array

i have get the first array of json but the second array come inside the first array in array ....:
how is solved it
i have get the tweet_image array inside the image array two array how is solve it
i have get the image path;
{
"feed": [
{
"tweet_id": "794",
"userid": "6",
"content": "<a href=http://www.punjabkesari.in/news/article-370994>http://www.punjabkesari.in/news/article-370994</a>",
"favorite_count": "0",
"reply_count": "0",
"retweet_count": "0",
"tweet_location": "",
"created_date": "2015-06-16 11:49:00",
"name": "amar bhanu",
"user_image": "http://sabakuch.com/public/images_upload/avatars/ozone/6_30_imageamar.jpg",
"tweet_images": {
"image": [
"http://sabakuch.com/public/images_upload/tweet/794_400_1434435540_album143443554069.jpg"
]
}
}
]
}
You can try this.
try {
JSONObject _jObject = new JSONObject("YOUR_JSON_STRING");
JSONArray _jArrayFeed = _jObject.getJSONArray("feed");
if (_jArrayFeed.length()>0) {
for (int i = 0; i < _jArrayFeed.length(); i++) {
JSONObject _subObj = _jArrayFeed.getJSONObject(i);
String _tweet_id = _subObj.getString("tweet_id");
String _userid = _subObj.getString("userid");
String _content = _subObj.getString("content");
String _favorite_count = _subObj.getString("favorite_count");
String _reply_count = _subObj.getString("reply_count");
String _retweet_count= _subObj.getString("retweet_count");
String _tweet_location = _subObj.getString("tweet_location");
String _created_date = _subObj.getString("created_date");
String _name = _subObj.getString("name");
String _user_image = _subObj.getString("user_image");
JSONObject _jObjtweet_images = _subObj.getJSONObject("tweet_images");
JSONArray _jArrayImages = _jObjtweet_images.getJSONArray("image");
if (_jArrayImages.length()>0) {
for (int j = 0; j < _jArrayImages.length(); j++) {
String _image = _jArrayImages.getString(j);
}
}
}
}
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
And let me know, if you have any issues.
Try this way
JSONArray array= jsonResponse.getJSONArray("feed");
JSONObject obj= array.getJSONObject(0);
JSONObject image= obj.getJSONObject("tweet_images");
JSONArray image_array= image.getJSONArray("image");
String url= image_array.getString(0);
hope it helps :-)

Get Specific Value from JSONArray

i got an jsonarray:
[
{
"ean": "8020079127",
"nr": "100",
"name": "Name1"
},
{
"ean": "8026180222",
"nr": "4",
"name": "Name2"
},
{
"ean": "6577426092",
"nr": "1",
"name": "Name3"
}
]
I need the value from "nr" depending on the "ean" means:
I got the ean 8026180222 (as string) and need the value from the "nr" (here "4"). how I can get it?
its possible without iterate over the whole array?
thank you
Try this:
// Use a map to store ean,nr (as key/value)
HashMap<String, String> jsonMap = new HashMap<String, String>();
// Load the data from json
JSONArray jsonArray= new JSONArray(yourJsonString);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObj = jsonArray.getJSONObject(i);
String ean = jsonObj.getString("ean");
String nr = jsonObj.getString("nr");
String name = jsonObj.getString("name");
jsonMap.put(ean, nr); // here you put ean as key and nr as value
}
To retrieve an nr value of a specific ean just call: jsonMap.get(yourEAN);
Example: String nr = jsonMap.get("8026180222");
List<NameValuePair> params = new ArrayList<NameValuePair>();
JsonObject json = jsonParser.makeHttpRequest(url, "GET", params);
Log.d("Tag", json.toString());
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
JSONArray jsnObj;
try {
jsnObj = json
.getJSONArray(TAG_ARRAY);
JSONObject obj = jsnObj
.getJSONObject(1);
String nr = obj.getString(TAG_NR);
}
Catch(Exception ex){}
}
}
If you want array you can use loops in json array.....................Hope it will help
Just define
private static final String TAG_SUCCESS = "success";
private static final String TAG_NR = "nr";
private static final String TAG_ARRAY = "array_name";

Categories

Resources