Help me parsing JSON. I parse this JSON without "moment" and don't know how parse with "moment".
My JSON response:
{
"A": [
{
"time0_90": "20",
"score": "0 : 0",
"team1": "Россия",
"team2": "Франция",
"group": "A",
"live": "1"
},
{
"time0_90": "20",
"score": "0 : 0",
"team1": "Португалия",
"team2": "Гондурас",
"group": "A",
"live": "0",
"time": "18:30",
"stadium": "",
"referee": "судья"
}
],
"B": [
{
"time0_90": "3",
"score": "1 : 0",
"moment": [
{
"class_moment": "g",
"name1": "Халк",
"time0_90Moment": "5",
"team": "1"
},
{
"class_moment": "sub",
"name1": "Фред",
"time0_90Moment": "50",
"team": "1",
"name2": "Жо"
}
],
"team1": "Бразилия",
"team2": "Испания",
"group": "B",
"live": "1"
}
],
"C": [],
"D": [],
"E": [],
"F": [
{
"time": "15:00",
"stadium": "Маракана",
"referee": "судья",
"team1": "Россия",
"team2": "Франция",
"group": "F",
"live": "0"
}
],
"G": [],
"H": []
}
This code is parse response without "moment". How to parse response with "moment" and save it in array?
JSONObject jsonResponse = new JSONObject(jsonResult);
for (int j=0; j<8; j++){
String[] groupName = {"A", "B", "C", "D", "E", "F", "G", "H"};
JSONArray jsonMainNode = jsonResponse.optJSONArray(groupName[j]);
if (jsonMainNode.length() == 0){ continue;}
else {
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
team1 = jsonChildNode.optString("team1");
team2 = jsonChildNode.optString("team2");
group = jsonChildNode.optString("group");
int live = jsonChildNode.getInt("live");
String time = null;
if (live == 1){
time = jsonChildNode.optString("time0_90")+"'";
score = jsonChildNode.optString("score");
}
else {
score = jsonChildNode.optString("time");
referee = jsonChildNode.optString("referee");
time = jsonChildNode.optString("stadium");
}
try this :
jsonArray moment = json.getJsonArray("B").getJsonObject(0).getJsonArray("moment");
String class = moment.getString("class_moment");
String name= moment.getString("name1");
String time= moment.getString("time0_90Moment");
String team= moment.getString("team");
I would recommend that you use a JSON Mapping library, like Jackson or GSON, manually parsing JSON is a waste of time and effort unless it is purely for educational purposes.
Other than that I assume the correct usage would be .optJSONArray("moment") follow by an iteration with a cast of each result to JSONObject or similar? Manually doing this is just a mess. ;o
I did it, here's the code
JSONObject jsonResponse = new JSONObject(jsonResult);
for (int j=0; j<8; j++){
String[] groupName = {"A", "B", "C", "D", "E", "F", "G", "H"};
JSONArray jsonMainNode = jsonResponse.optJSONArray(groupName[j]);
if (jsonMainNode.length() == 0){ continue;}
else {
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
team1 = jsonChildNode.optString("team1");
team2 = jsonChildNode.optString("team2");
group = jsonChildNode.optString("group");
int live = jsonChildNode.getInt("live");
String time = null;
if (live == 1){
time = jsonChildNode.optString("time0_90")+"'";
score = jsonChildNode.optString("score");
JSONArray jsonMoment = jsonChildNode.optJSONArray("moment");
if (jsonMoment == null)
{
class_moment=new String[1];
name1 = new String[1];
name2 = new String[1];
name1 = new String[1];
time0_90Moment = new String[1];
team = new int[1];
}
else {
class_moment=new String[jsonMoment.length()];
name1 = new String[jsonMoment.length()];
name2 = new String[jsonMoment.length()];
name1 = new String[jsonMoment.length()];
time0_90Moment = new String[jsonMoment.length()];
team = new int[jsonMoment.length()];
for (int k = 0; k < jsonMoment.length(); k++) {
JSONObject jsonChildMoment = jsonMoment.getJSONObject(k);
class_moment[k] = jsonChildMoment.optString("class_moment");
name1[k] = jsonChildMoment.optString("name1");
name2[k] = jsonChildMoment.optString("name2");
time0_90Moment[k] = jsonChildMoment.optString("time0_90Moment");
team[k] = jsonChildMoment.getInt("team");
}}
}
else {
score = jsonChildNode.optString("time");
referee = jsonChildNode.optString("referee");
time = jsonChildNode.optString("stadium");
}
Related
This is my json data I have created ui design using this json string but by the time of updating I am confused about this how to correctly get EditText values and how to update
{
"SingleExtras": [{
"Id": 1,
"name": "size",
"isEnabled": 1,
"values": [{
"extraId": 30,
"objId": "Gb39Rpmdl9",
"extraName": "Small",
"extraPrice": 15,
"currency": "Aed",
"isEnabled": 1
},
{
"extraId": 30,
"objId": "kknwBtS9zJ",
"extraName": "Medium",
"extraPrice": 18,
"currency": "Aed",
"isEnabled": 0
},
{
"extraId": 30,
"objId": "d5YfEGAgMt",
"extraName": "Large",
"extraPrice": 20,
"currency": "Aed",
"isEnabled": 1
}
]
},
{
"Id": 5,
"name": "Milk",
"isEnabled": 1,
"values": [{
"extraId": 30,
"objId": "8obBCWDXbh",
"extraName": "LowFatMilk",
"extraPrice": 0,
"currency": "Aed",
"isEnabled": 1
},
{
"extraId": 31,
"objId": "CC629INXuP",
"extraName": "FullFatMilk",
"extraPrice": 0,
"currency": "Aed",
"isEnabled": 1
}
]
}
],
"Extras": [{
"extraId": 5,
"objId": "PxDQX3LGU2",
"extraName": "ExtraShot",
"extraPrice": 5,
"currency": "Aed",
"isEnabled": 1
}]
}
I'm using the code below to get the modified EditText values in that
for(int i=0; i < allEds.size(); i++){
pricelist.add(allEds.get(i).getText().toString().trim());
priceidslist.add(allEds.get(i).getId());
}
This is nested array function here in loop I'm getting array index{0,1,2,0,1,2,0} like this i have all editetxt prices list by using im not able to update index position values mismatching
public void jsonarray(JSONArray arry){
try {
for (int j = 0; j < arry.length(); j++) {
JSONObject rw = arry.getJSONObject(j);
String extraId = rw.optString("extraId");
String objId = rw.optString("objId");
String extraName = rw.optString("extraName");
String extraPrice = rw.optString("extraPrice");
String currenc = rw.optString("currency");
String chksts = rw.optString("isEnabled");
if (namechklist.contains(extraName)) {
rw.put("isEnabled", "1");
}
if (nameunchklist.contains(extraName)) {
rw.put("isEnabled", "0");
}
if(allnames.contains(extraName)){
rw.put("extraPrice", pricelist.get(j));
}
Log.d("res", "jsonarray:loop "+arry.toString());
}
Log.d("res", "jsonarray: "+arry.toString());
}
catch (JSONException e) {
e.printStackTrace();
}
}
Anyone please suggest me which way is better to achieve this logic correctly
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject row = jsonArray.getJSONObject(i);
String itemid = row.optString("id");
JSONArray arry = row.getJSONArray("values");
if(i == 0){
}
else{
final int ar = arry.length();
final int tot = g + ar ;
int h = 0;
for (int j = g ; j < tot; j++) {
JSONObject rw = arry.getJSONObject(h);
String extraName = rw.optString("extraName");
String extraId = rw.optString("extraId");
if(namechklist.size() > 0){
if(namechklist.contains(extraName)){
rw.put("isEnabled","1");
}
}
if(nameunchklist.size()>0){
if(nameunchklist.contains(extraName)){
rw.put("isEnabled","0");
}
}
if(j >= arry.length()){
}else{
String gh = String.valueOf(priceidslist.get(j));
if(gh.equals(extraId)){
rw.put("extraPrice",pricelist.get(j));
}
}
h++;
}
g = arry.length();
}
}
Log.d("chk", "res:last "+jsonArray.toString());
}
JSONArray extraArray = obj.getJSONArray("Extras");
for (int i = 0; i < extraArray.length(); i++) {
JSONObject rw = extraArray.getJSONObject(i);
String extraName = rw.optString("extraName");
String extraId = rw.optString("extraId");
if(exnamechklist.size() > 0){
if(exnamechklist.contains(extraName)){
rw.put("isEnabled","1");
}
}
if(exnameunchklist.size()>0){
if(exnameunchklist.contains(extraName)){
rw.put("isEnabled","0");
}
}
}
I just changed for loop condition and changed format of getting json values now its working fine
How do I associate the ids and names from a JSON file with the position parameter in onitemclicklistener in Android Studio?
I have a JSON data file containing ids and names and I want to retrieve them into a listview onTextChangedQuery in autocomplete search. I have done that but now I can't relate it to their respective position in OnItemClickListener.
This is the JSON file
"data": [
{
"id": "26",
"fullname": "Abbas",
"address": "mingora"
},
{
"id": "28",
"fullname": "shakeel",
"address": "mingora"
},
{
"id": "29",
"fullname": "Fayaz",
"address": "Odigram"
},
{
"id": "30",
"fullname": "Fayaz",
"address": "Odigram"
},
{
"id": "31",
"fullname": "m fayaz",
"address": "odigram"
}
]
The following is the code:
public void onResponse(String response) {
try {
JSONObject Jobject = new JSONObject(response);
JSONArray DATA = Jobject.getJSONArray("data");
for (int i = 0; i < DATA.length(); i++) {
jsonObject = DATA.getJSONObject(i);
id = jsonObject.getString("id");
name = jsonObject.getString("fullname");
// getting id from json
String newId = id;
int currentid = myids.length;
int newSize1 = currentid + 1;
String[] ArrayId = new String[newSize1];
for (int k = 0; k < currentid; k++) {
ArrayId[k] = myids[k];
}
ArrayId[newSize1 - 1] = newId;
myids = ArrayId;
//the following code adds new item to the array from the json object
String newItem = name;
int currentSize = contactList.length;
int newSize = currentSize + 1;
String[] tempArray = new String[newSize];
for (int j = 0; j < currentSize; j++) {
tempArray[j] = contactList[j];
}
tempArray[newSize - 1] = newItem;
contactList = tempArray;
ArrayAdapter arrayAdapter = new ArrayAdapter<String>(BloodDonerActivity.this, R.layout.list_item, R.id.textView, contactList);
lv.setAdapter(arrayAdapter);
}
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int pos, long l) {
String userId = myids[pos];
Toast.makeText(getApplicationContext(), userId, Toast.LENGTH_SHORT).show();
//id of user on position
}
});
I am trying to fetch data from MySQL database and trying to show it into a table. For this I am using volley.
JSONArray result = response.getJSONArray("result");
for (int i = 0; i < result.length(); i++) {
JSONObject jsonObject = result.getJSONObject(i);
String name = jsonObject.getString("name");
String phone = jsonObject.getString("phone");
String email = jsonObject.getString("email");
String j = String.valueOf(i);
data = new String[][]{{j, name, email, phone}};
tableView.setDataAdapter(new SimpleTableDataAdapter(getActivity(), data));
}
My json array
{
"result": [
{
"sl": "36",
"user_id": "575512",
"email": "m#gmail.com",
"password": "123",
"name": "Moderator",
"gender": "Male",
"phone": "1223345",
"lvl": "Moderator",
"stat": "1"
},
{
"sl": "68",
"user_id": "814769",
"email": "m2#gmail.com",
"password": "1WCcvnhp",
"name": "Test Moderator",
"gender": "Male",
"phone": "7412589630",
"lvl": "Moderator",
"stat": "1"
}
]
}
The problem is I am getting only the last value from jsonArray, because the String array is resetting itself.
data = new String[][]{{j, name, email, phone}};
I want to get all the values available in the jsonArray.
I am using the following dependencies for table
de.codecrafters.tableview:tableview:2.8.0
Try like this
JSONArray result = response.getJSONArray("result");
for (int i = 0; i < result.length(); i++) {
JSONObject jsonObject = result.getJSONObject(i);
String name = jsonObject.getString("name");
String phone = jsonObject.getString("phone");
String email = jsonObject.getString("email");
String j = String.valueOf(i);
data = new String[][]{{j, name, email, phone}};
}
tableView.setDataAdapter(new SimpleTableDataAdapter(getActivity(), data));
After getting all values in array, add that array to tableview
I am building an Android app and are collecting data from my remote API (using Volley)
and I need to parse the response. I know how to get the "projects" array but how can I get the title for each project (please note the project key for each project).
{
"code": 200,
"total": 4,
"projects": [
{
"project": {
"id": 1,
"title": "A nice long title",
"latitude": 56.0293783,
"longitude": 12.7256732,
"created_at": "2013-10-20T20:57:00+02:00",
"created_at_human": "5 months",
"total_tasks": 7,
"description": "This is a description.",
"address": "simple highway 22",
"zipcode": "25656",
"city": "florida"
}
},
{
"project": {
"id": 2,
"title": "A nice long title",
"latitude": 56.0293783,
"longitude": 12.7256732,
"created_at": "2013-10-20T20:57:00+02:00",
"created_at_human": "5 months",
"total_tasks": 7,
"description": "This is a description.",
"address": "simple highway 22",
"zipcode": "25656",
"city": "florida"
}
}
]
}
This is the code I use now and that needs to be modified:
JSONArray jsonPosts = mData.getJSONArray("projects");
ArrayList<HashMap<String, String>> blogPosts = new ArrayList<HashMap<String, String>>();
for (int i = 0; i < jsonPosts.length(); i++) {
JSONObject post = jsonPosts.getJSONObject(i);
Log.e("OUTPUT", "THE POST: " + post);
}
This outputs:
E/OUTPUT﹕ THE POST: {"project":{"id":1,"title":"A nice long title","total_tasks":7,"address":"simple highway 22","description":"This is a description.","zipcode":"25656","created_at":"2013-10-20T20:57:00+02:00","longitude":12.7256732,"created_at_human":"5 MåNADER","latitude":56.0293783,"city":"florida"}}
How can I access the title for each?
Each jSONObject item contains a key and jSONObject. I think you need to get jSONObject from item in Array then get title and city.
I hope it will helpful for you........
JSONArray jsonPosts = mData.getJSONArray("projects");
ArrayList<HashMap<String, String>> blogPosts = new ArrayList<HashMap<String, String>>();
for (int i = 0; i < jsonPosts.length(); i++) {
JSONObject post = jsonPosts.getJSONObject(i);
JSONObject innerjson = post.getJSONObject("project");
String title = innerjson.getString(KEY_TITLE);
title = Html.fromHtml(title).toString();
String city = innerjson.getString(KEY_CITY);
city = Html.fromHtml(city).toString();
HashMap<String, String> blogPost = new HashMap<String, String>();
blogPost.put(KEY_TITLE, title);
blogPost.put(KEY_CITY, city);
blogPosts.add(blogPost);
}
String[] keys = {KEY_TITLE, KEY_CITY};
int[] ids = { R.id.top_label, R.id.bottom_label};
SimpleAdapter adapter = new SimpleAdapter(this, blogPosts, R.layout.list_item, keys, ids);
setListAdapter(adapter);
This is a JSONArray and not a JSONObject - to make a JSONObject from it, use
JSONObject jsonObject = jsonArray.getJSONObject(0);
this gets the first JSONObject from this JSONArray.
If you have multiple JSONObjects, use this:
JSONObject jsonObject;
for(int n = 0; n < jsonArray.length(); n++)
{
jsonObject = jsonArray.getJSONObject(n);
}
To get the values:
jsonObject.getString("name");
{
"204": {
"host": "https:\/\/abc.com\/production-source\/ChangSha\/2013\/12\/02\/0\/0\/A\/Content\/",
"timestamp": 1385909880,
"cover": ["17\/Pg017.png",
"18\/Pg018.png",
"1\/Pg001.png",
"2\/Pg002.png"],
"year": "2013",
"month": "12",
"day": "02",
"issue": "2013-12-02",
"id": "204"
},
"203": {
"host": "https:\/\/abc.com\/production-source\/ChangSha\/2013\/12\/01\/0\/0\/A\/Content\/",
"timestamp": 1385806902,
"cover": ["1\/Pg001.png",
"2\/Pg002.png",
"3\/Pg003.png",
"4\/Pg004.png"],
"year": "2013",
"month": "12",
"day": "01",
"issue": "2013-12-01",
"id": "203"
},
"202": {
"host": "https:\/\/abc.com\/production-source\/ChangSha\/2013\/11\/30\/0\/0\/A\/Content\/",
"timestamp": 1385720451,
"cover": ["1\/Pg001.png",
"2\/Pg002.png",
"3\/Pg003.png",
"4\/Pg004.png"],
"year": "2013",
"month": "11",
"day": "30",
"issue": "2013-11-30",
"id": "202"
}
}
The above sample json array , how to get the 204, 203 and 202? Thanks
I tried:
JSONArray issueArray = new JSONArray(jsonContent);
for (int j = 0; j < issueArray.length(); j++) {
JSONObject issue = issueArray.getJSONObject(j);
String _pubKey = issue.getString(0);
}
above sample json array , how to get the 204, 203 and 202?
No, current String is JSONObject instead of JSONArray. you should get Iterator using JSONObject. keys () if inner JSONObject keys dynamic as:
JSONObject issueObj = new JSONObject(jsonContent);
Iterator iterator = issueObj.keys();
while(iterator.hasNext()){
String key = (String)iterator.next();
JSONObject issue = issueObj.getJSONObject(key);
// get id from issue
String _pubKey = issue.optString("id");
}
Answer given by Mr. K is also right but you can also use jsonObject names() method. please find the sample code
for(int i = 0; i<jsonobject.length(); i++){
Log.e(TAG, "Key = " + jsonobject.names().getString(i) + " value = " + jsonobject.get(jsonobject.names().getString(i)));
}
I hope dis will help you
User this method to iterate json dynamically
private void parseJson(JSONObject data) {
if (data != null) {
Iterator<String> it = data.keys();
while (it.hasNext()) {
String key = it.next();
try {
if (data.get(key) instanceof JSONArray) {
JSONArray arry = data.getJSONArray(key);
int size = arry.length();
for (int i = 0; i < size; i++) {
parseJson(arry.getJSONObject(i));
}
} else if (data.get(key) instanceof JSONObject) {
parseJson(data.getJSONObject(key));
} else {
System.out.println("" + key + " : " + data.optString(key));
}
} catch (Throwable e) {
System.out.println("" + key + " : " + data.optString(key));
e.printStackTrace();
}
}
}
}
You can also use names() as below to get the keys as JSONArray :
JSONArray jArray = jsonObject.names();
int len = jsonObject.length();
for (int i=0; i<len; i++) {
String keyName = (String)jArray.get(i);
JSONObject jValue = jsonObject.getJSONObject(keyName);
String _pubKey = jValue.optString("id");
//get the other values from jValue
}
Here you are trying to get JSONArray but in json response it is JSONObject.
Use following code.
JSONObject issueObject = new JSONObject(jsonContent);
String _pubKey = issueObject.getString(0);