i have parser function that parse json array and return arrays that i use it in a list adapter and then the adapter is used by a recyclerview .it's giving me the actual length but only the first element of the arrays is filled while the others return NULL
that is my code
public void parsee_item() {
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(json);
final JSONArray userss = jsonObject.getJSONArray(JSON_ARRAY);
item_id = new String[userss.length()];
item_owner = new String[userss.length()];
item_images = new String[userss.length()];
item_names = new String[userss.length()];
item_price = new String[userss.length()];
item_place = new String[userss.length()];
JSONObject jo = null;
for (int i = 0; i < userss.length();i++) {
jo = userss.getJSONObject(i);
Log.d("alrsp", jo.toString());
item_id[i] = jo.getString(KEY_ID);
item_owner[i] = jo.getString(KEY_OWNER);
item_images[i] = jo.getString(KEY_IMAGE);
item_names[i] = jo.getString(KEY_NAME);
item_price[i] = jo.getString(KEY_PRICE);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
the json is
{
"result": [{
"item_id": "10",
"owner": "user",
"item_type_id": "1",
"url1": "http:\/\/localhost:8080\/market\/items\/14.1.png",
"name": "jc",
"price": "76"
}, {
"item_id": "12",
"owner": "user",
"item_type_id": "1",
"url1": " http:\/\/localhost:8080\/market\/items\/14.1.png",
"name": "nzbsbsb",
"price": "0"
}, {
"item_id": "13",
"owner": "user",
"item_type_id": "1",
"url1": " http:\/\/localhost:8080\/market\/items\/14.1.png",
"name": "uygf",
"price": "0"
}]
}
and this screenshot of the list
enter image description here
it's not suggested parsing json yourself ,use a Json Parse Util such as Gson or fastJson instead .
I used your code, debug, and found values are updated their is no error with JSON paring, So check your recycler view adapter code or share it
Replace this line
jo = userss.getJSONObject(4);
with this
jo = userss.getJSONObject(i);
JSONObject jo = null;
for (int i = 0; i < userss.length();i++) {
jo = userss.getJSONObject(i);
Log.d("alrsp", jo.toString());
item_id[i] = jo.getString(KEY_ID);
item_owner[i] = jo.getString(KEY_OWNER);
item_images[i] = jo.getString(KEY_IMAGE);
item_names[i] = jo.getString(KEY_NAME);
item_price[i] = jo.getString(KEY_PRICE);
item_place[i] = jo.getString("place");
}
the problem with ur code is you use hardcode value 4
jo = userss.getJSONObject(4);
insted of this use
jo = userss.getJSONObject(i);
at each and every time you are parsing the index 4 jsonObject information
public void parsee_item() {
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(json);
final JSONArray userss = jsonObject.getJSONArray(JSON_ARRAY);
item_id = new String[userss.length()];
item_owner = new String[userss.length()];
item_images = new String[userss.length()];
item_names = new String[userss.length()];
item_price = new String[userss.length()];
item_place = new String[userss.length()];
JSONObject jo = null;
for (int i = 0; i < userss.length();) {
jo = userss.getJSONObject(i);
Log.d("alrsp", jo.toString());
item_id[i] = jo.getString(KEY_ID);
item_owner[i] = jo.getString(KEY_OWNER);
item_images[i] = jo.getString(KEY_IMAGE);
item_names[i] = jo.getString(KEY_NAME);
item_price[i] = jo.getString(KEY_PRICE);
item_place[i] = jo.getString("place");
i++;
}
} catch (JSONException e) {
e.printStackTrace();
}
}
if you use this type of parsing it may lead to null pointer exception
You can parse above JSON as follows
private void jsonParse(String response) throws JSONException {
JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.getJSONArray("result");
if (jsonArray != null && jsonArray.length() > 0) {
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject object = jsonArray.getJSONObject(i);
if (object != null) {
String itemId = object.getString("item_id");
String owner = object.getString("owner");
String item_type_id = object.getString("item_type_id");
String url1 = object.getString("url1");
String name = object.getString("name");
String price = object.getString("price");
}
}
}
}
i was receiving a parameter that wasn't being sent by the jsonarray
item_place[i] = jo.getString("place")
Related
I have problem when I try to get data from a JSON array in Android Studio.
I want to get data from year 2015, 2016 and 2018 populate them in different textviews.
This is my JSON:
"data": [
{
"id": "7",
"kecamatan": "Blambangan Umpu",
"year": {
"2015": {
"id": "27",
"value": "60200"
},
"2016": {
"id": "41",
"value": "61516"
},
"2018": {
"id": "7",
"value": ""
}
},
"avg": 2.14
},
and this is my mainactivity
try {
JSONObject jsonObject = new JSONObject(s);
JSONArray array = jsonObject.getJSONArray("data");
// JSONArray array = new JSONArray(s);
for (int i = 0; i < array.length(); i ++) {
JSONObject o = array.getJSONObject(i);
String id = o.getString("id");
String kec = o.getString("kecamatan");
String avg = o.getString("avg");
String tahun = o.getString("year");
// JSONArray array2 = o.getJSONArray("year");
// for (int j = 0; j<array2.length(); j++) {
// JSONObject p = array2.getJSONObject(j);
// String value = p.getString("value");
ListItem item = new ListItem(id, kec, avg, tahun, avg);
listItems.add(item);
// }
}
adapter = new MyAdapter(listItems, getApplicationContext());
recyclerView.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
year is a JSONObject with 2015,2016 and 2018 as keys and JSONObject as values, So get year JSONObject and then get keys and values by iterating it
for (int i = 0 ; i<array.length(); i++) {
JSONObject o = array.getJSONObject(i);
String id = o.getString("id");
String kec = o.getString("kecamatan");
String avg = o.getString("avg");
JSONObject yearObject = o.JSONObject("year"); //get JSONObject
Iterator<String> itr = yearObject.keys();
while(itr.hasNext()) {
String year = itr.next();
JSONObject obj = o.get("year"); //2015
System.out.println(obj.getString("id")); //27
System.out.println(obj.getString("value")); //60200
}
//Add required fields into `ListItem`
ListItem item = new ListItem(id,kec,avg,tahun,avg);
listItems.add(item);
}
I try to create a desired json structure in java but I get only last value in json structure since i creating json outside for loop. if i create it in nested for loop then its not give me desired structure of json.
My code is here:-
public static void main(String[] args) {
JSONObject TP1 = new JSONObject();
String[] alias = {"topping","cake"};
String[] entityType = {"Topping","cake"};
String[] textString = {"pizza","pancake"};
String[] usersays_text = {"I want ","I want "};
for(String usy:usersays_text)
{
TP1.put("text",usy.toString());
}
JSONObject TP2 = new JSONObject();
for(String tS:textString)
{
TP2.put("text",tS.toString());
}
for(String eT:entityType)
{
TP2.put("entityType",eT.toString());
}
for(String al:alias)
{
TP2.put("alias",al.toString());
}
JSONArray JSA=new JSONArray();
JSA.put(TP1);
JSA.put(TP2);
JSONObject root1= new JSONObject();
root1.put("parts", JSA);
JSONArray JSA4=new JSONArray();
JSA4.put(root1);
JSONObject root3= new JSONObject();
root3.put("TP", JSA4);
//To print
JSONObject json = new JSONObject(root3.toString()); // Convert text to object
System.out.println(json.toString(4));
}
which results me following json structure:-
{
"TP": [{
"parts": [{
"text": "I want "
},
{
"entityType": "cake",
"alias": "cake",
"text": "pancake"
}
]
}]
}
Desired structure for each value of string array -
for ex:
{
"TP": [
{
"parts": [
{
"text": "I want "
},
{
"alias": "topping",
"text": "pizza",
"entityType": "Topping"
}
]
},
{
"parts": [
{
"text": "I want "
},
{
"alias": "cake",
"entityType": "cake",
"text": "pancake"
}
]
}
]
}
Your jsonobject construction is wrong. In 'jsonobject' key is in unique,
when you try it like this
for(String usy:usersays_text)
{
TP1.put("text",usy.toString());
}
the same key is present in the json object and values get replaced.
Please try the below code, it constructs the json object as expected.
public static void main(String args[]) {
JSONObject TP1 = new JSONObject();
String[] alias = {"topping","cake"};
String[] entityType = {"Topping","cake"};
String[] textString = {"pizza","pancake"};
String[] usersays_text = {"I want ","I want "};
JSONObject jobj = new JSONObject();
JSONArray jarr = new JSONArray();
for(int index = 0; index < usersays_text.length; index++)
{
JSONObject parts = new JSONObject();
JSONArray partsArr = new JSONArray();
JSONObject partsObj = new JSONObject();
partsObj.put("text", usersays_text[index].toString());
JSONObject cont = new JSONObject();
cont.put("alias", alias[index].toString());
cont.put("text", textString[index].toString());
cont.put("entityType", entityType[index].toString());
partsArr.put(partsObj);
partsArr.put(cont);
parts.put("parts", partsArr);
jarr.put(parts);
}
jobj.put("trainingPhrases", jarr);
System.out.println(jobj.toString(4));
}
You have to use single loop, Assume each array has same length, Following code could help you
public static void main(String[] args) throws Exception {
String[] alias = {"topping", "cake"};
String[] entityType = {"Topping", "cake"};
String[] textString = {"pizza", "pancake"};
String[] usersays_text = {"I want ", "I want "};
JSONArray parts = new JSONArray();
for (int i = 0; i < usersays_text.length; i++) {
JSONArray JSA = new JSONArray();
JSONObject TP1 = new JSONObject();
TP1.put("text", usersays_text[i]);
JSONObject TP2 = new JSONObject();
TP2.put("text", textString[i]);
TP2.put("entityType", entityType[i]);
TP2.put("alias", alias[i]);
JSA.put(TP1);
JSA.put(TP2);
parts.put( JSA);
}
JSONObject partsObject = new JSONObject();
partsObject.put("parts",parts);
JSONObject root= new JSONObject();
root.put("trainingPhrases", partsObject);
//To print
JSONObject json = new JSONObject(root.toString()); // Convert text to object
System.out.println(json.toString(4));
}
I have a json string string from which I want to get the values. It is in key pair form so I want the values for each key.
I tried to get the values but I am not getting it.
Json String is like :
{
"document": {
"xmlns:xsi": "http:\/\/www.w3.org\/2001\/XMLSchema-instance",
"xsi:schemaLocation": "http:\/\/ocrsdk.com\/schema\/recognizeard-1.0.xsd http:\/\/ocrsdk.com\/schema\/recognized-1.0.xsd",
"xmlns": "http:\/\/ocrsdk.com\/schema\/recognize-1.0.xsd",
"businessCard": {
"imageRotation": "noRotation",
"field":
[{
"type": "Name",
"value": "Rafcev B. Agnrwal"
}, {
"type": "Company",
"value": "VJ>"
}, {
"type": "Text",
"value": "Dr. Rafcev B. Agnrwal\nMOB 0324%\nun\n) AOM*. founts. sso\nVJ>\nT"
}]
}
}
}
I want to get values of "Name", "Address", "Company" etc.
I tried to get like this:
JSONArray array;
if(mIntent.getStringExtra("jsonString") != null) {
Log.d("json", mIntent.getStringExtra("jsonString"));
try {
JSONObject object = new JSONObject(mIntent.getStringExtra("jsonString"));
array = object.getJSONArray("field");
for (int i = 0; i < array.length(); i++) {
JSONObject subObject1 = array.getJSONObject(i);
edt_FirstName.setText(object.getString("Name"));
}
} catch (JSONException e) {
}
Can anyone help me out please? Thank you..
EDIT:
I tried to check values like this:
for (int i = 0; i < array.length(); i++) {
JSONObject subObject1 = array.getJSONObject(0);
String type = subObject1.getString("type");
String value = subObject1.getString("value");
if (type.equals("Name")) {
edt_FirstName.setText(value);
}
if(type.equals("Address"))
{
edt_address.setText(value);
}
if(type.equals("Company"))
{
edt_company.setText(value);
}
if(type.equals("Mobile"))
{
edt_Mobile.setText(value);
}
}
I want to get all the values from field array and set to the text view, but I am getting only the Name value and not the others.
Also I could get one field as twice like Mobile I can get twice, so I want to combine both the Mobile values and show it.
So your json object is as follow:
{
"document": {
"xmlns:xsi": "http:\/\/www.w3.org\/2001\/XMLSchema-instance",
"xsi:schemaLocation": "http:\/\/ocrsdk.com\/schema\/recognizeard-1.0.xsd http:\/\/ocrsdk.com\/schema\/recognized-1.0.xsd",
"xmlns": "http:\/\/ocrsdk.com\/schema\/recognize-1.0.xsd",
"businessCard": {
"imageRotation": "noRotation",
"field":
[{
"type": "Name",
"value": "Rafcev B. Agnrwal"
}, {
"type": "Company",
"value": "VJ>"
}, {
"type": "Text",
"value": "Dr. Rafcev B. Agnrwal\nMOB 0324%\nun\n) AOM*. founts. sso\nVJ>\nT"
}]
}
}
}
You first need to get "document" as JSONObject and then get "businessCard" as JSONObject and then you can get "field" as JSONArray:
if(mIntent.getStringExtra("jsonString") != null) {
Log.d("json", mIntent.getStringExtra("jsonString"));
try {
JSONObject object = new JSONObject(mIntent.getStringExtra("jsonString"));
JSONArray array = object.getJSONObject("document").getJSONObject("businessCard").getJSONArray("field");
for (int i = 0; i < array.length(); i++) {
JSONObject subObject = array.getJSONObject(i);
String type = subObject.getString("type");
String value = subObject.getString("value");
if (type.equals("Name")) {
String prevValue = edt_FirstName.getText();
edt_FirstName.setText((TextUtils.isEmpty(prevValue) ? "" : prevValue + ",") + value);
}
}
} catch (JSONException e) { }
}
Try this code, Hope it will help you.
try
{
JSONObject jsonObject = new JSONObject();
JSONObject documentObject = jsonObject.getJSONObject("document");
JSONObject businessCardObject = documentObject.getJSONObject("businessCard");
String imgRotation = businessCardObject.getString("imageRotation");
JSONArray array = businessCardObject.getJSONArray("field");
for (int i = 0; i < array.length() ; i++)
{
JSONObject arrObj = array.getJSONObject(i);
String type = arrObj.getString("type");
String value = arrObj.getString("value");
Log.e(TAG, "type=="+type);
Log.e(TAG, "value=="+value);
}
}
catch (Exception ex)
{
ex.printStackTrace();
}
here is code
private void convertJsonToDto(String jsonNewString) {
JSONObject jsonObj = new JSONObject(jsonNewString);
String RecordLocator = (String) jsonObj.get("obj");
String FirstName = (String) jsonObj.getJSONObject("Customer").get("FirstName");
JSONArray array = new JSONObject(jsonNewString).getJSONArray("Array");
JSONObject jsonObject = array.getJSONObject(0);
String str = jsonObject.getString("object");
}
I'v try to get an value from a json data (YouTube V3 API).
String jsonText = readFromUrl(channerUrl);// channerUrl = Youtube V3 API Link
JSONObject json = new JSONObject(jsonText);
System.out.println(json.getString("videoId"));
But i have this in my log :
I/System.out: org.json.JSONException: No value for videoId
The data from YouTube is :
{
"kind": "youtube#playlistItemListResponse",
"etag": "\"xxxx"",
"nextPageToken": "xxx",
"pageInfo": {
"totalResults": 321,
"resultsPerPage": 1
},
"items": [
{
"kind": "youtube#playlistItem",
"etag": "\"xxxx"",
"id": "xxxx",
"contentDetails": {
"videoId": "The Value Want"
}
}
]
}
Why i have No value for videoId ?
Thank you
EDIT (didn't work too) : (jsonText) is the link of the JSON Data
JSONObject json = new JSONObject(jsonText);
List<String> list = new ArrayList<String>();
JSONArray array = json.getJSONArray("items");
for(int i = 0 ; i < array.length() ; i++){
list.add(array.getJSONObject(i).getString("contentDetails"));
System.out.println(json.getString("contentDetails"));
}
Because videoId is under items object.
Get item first then get its first child then fet the videoId
Edit: use
array.getJSONObject(i).getJSONObject("contentDetails").getString("videoId")
And remove the println line
Then outside the loop just print the list that contains the videoIds
use this code :
JSONObject json = new JSONObject(jsonText);
List<String> list = new ArrayList<String>();
JSONArray array = null;
try {
array = json.getJSONArray("items");
} catch (JSONException e) {
e.printStackTrace();
}
for(int i = 0 ; i < array.length() ; i++){
// list.add(array.getJSONObject(i).getString("contentDetails"));
try {
System.out.println(array.getJSONObject(i).getJSONObject("contentDetails").getString("videoId"));
} catch (JSONException e) {
e.printStackTrace();
}
}
try
{
JSONObject mJsonObject = new JSONObject(strValue);
JSONArray items = mJsonObject.getJSONArray("items");
String nextToken = mJsonObject.getString("nextPageToken").toString();
for(int i = 0;i<items.length();i++)
{
JSONObject snipetts = items.getJSONObject(i);
JSONObject snipet = snipetts.getJSONObject("snippet");
JSONObject thumbnails = snipet.getJSONObject("thumbnails");
JSONObject highImage = thumbnails .getJSONObject("high");
String title = snipet.get("title").toString();
String urlImage = highImage.get("url").toString();
String videoID = snipetts.getString("id");
String description = snipet.getString("description");
String publishDate = snipet.getString("publishedAt");
}
}
catch (Exception e)
{
e.printStackTrace();
}
I'm working on parsing JSON file in my java and the JSON file goes like this
{"System":[{"System1":{"DisplayName":"fabcd","InternalName":"AD","SystemCode":"0001","SystemName":"vnid"},"System2":{"DisplayName":"akdfkajfl","InternalName":"AD","SystemCode":"0001","SystemName":"kjdfkafdk"}}]}
I cannot access the all objects inside "System" array. Please help me on this. My code is this
Systems = jObj.getJSONArray("System");
Log.d("Array", Systems.toString());
JSONObject first = Systems.getJSONObject(0);
Log.d("CSystems",first.toString());
// looping through All Contacts
for(int i = 0; i <=Systems.length(); i++){
JSONObject c = Systems.getJSONObject(i);
Log.d("SubSystems", Systems.getString(0));
}
Thanks.
Shouldn't for loop be looping over first instead of Systems? (With changes to account for the fact it's an object, not an array.)
To parse
try
{
JSONObject jObj = new JSONObject("My Json string");
JSONArray jr = jObj.getJSONArray("System");
JSONObject jb= jr.getJSONObject(0);
JSONObject system1 = jb.getJSONObject("System1");
String name = system1.getString("DisplayName");
String internalname = system1.getString("InternalName");
String SystemCode = system1.getString("SystemCode");
String SystemName = system1.getString("SystemName");
JSONObject system2 = jb.getJSONObject("System2");
String name1= system2.getString("DisplayName");
String internalname1 = system2.getString("InternalName");
String SystemCode1 = system2.getString("SystemCode");
String SystemName1 = system2.getString("SystemName");
Log.i("..........",name+"..."+internalname+"..."+SystemCode+"..."+SystemName);
Log.i("..........",name1+"..."+internalname1+"..."+SystemCode1+"..."+SystemName1);
}catch(Exception e)
{
e.printStackTrace();
}
or
Same as above.
try
{
JSONObject jObj = new JSONObject("My json string");
JSONArray jr = jObj.getJSONArray("System");
for(int i = 0; i<jr.length(); i++){
JSONObject c = jr.getJSONObject(i);
for(int j = 1;j<3; j++){
JSONObject jb = c.getJSONObject("System"+(j));
Log.i("SubSystems", jb.getString("DisplayName"));
Log.i("SubSystems", jb.getString("InternalName"));
Log.i("SubSystems", jb.getString("SystemCode"));
Log.i("SubSystems", jb.getString("SystemName"));
}
}
}catch(Exception e)
{
e.printStackTrace();
}
or change your json to
{
"System": [
{
"DisplayName": "fabcd",
"InternalName": "AD",
"SystemCode": "0001",
"SystemName": "vnid"
},
{
"DisplayName": "akdfkajfl",
"InternalName": "AD",
"SystemCode": "0001",
"SystemName": "kjdfkafdk"
}
]
}
To parse. Changing json to above parsing is much more easier.
try
{
JSONObject jObj = new JSONObject("My json string);
JSONArray jr = jObj.getJSONArray("System");
for(int i = 0; i<jr.length(); i++){
JSONObject c = jr.getJSONObject(i);
Log.i("SubSystems", c.getString("DisplayName"));
Log.i("SubSystems", c.getString("InternalName"));
Log.i("SubSystems", c.getString("SystemCode"));
Log.i("SubSystems", c.getString("SystemName"));
}
}catch(Exception e)
{
e.printStackTrace();
}
You can also look at https://code.google.com/p/google-gson/