How to get inner array data - android

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");

Related

Set value inside table from database using array

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

how to parse this type json array in android [duplicate]

This question already has answers here:
How do I parse JSON in Android? [duplicate]
(3 answers)
Closed 5 years ago.
this is array which i have
[ {
"comment": "Sir, 2nd paper qualifying hai ya Uski bhi merit banegi?",
"user": "Sameer",
"image": "https://jdcivils.org/images/co.png",
"date": "04/Sep/2016",
"reply": [
{
"comment": "Abhi qualifying nhi hai,iske marks merit list me judte hain",
"user": "Admin",
"image": "https://jdcivils.org/images/co.png",
"date": "04/Sep/2016"
}
]
},
{
"comment": "Cgpsc me hight kis kis post ke liye jaruri hoti hai..\r\nplss btayega koi??",
"user": "Vinod kumar Yadav",
"image": "https://jdcivils.org/images/co.png",
"date": "29/Aug/2016",
"reply": ""
},
{
"comment": "Sir Cgpsc Me gen. category walo Ko Psc k attempts ki koi limit Hoti Hai kya??",
"user": "Vinod kumar Yadav",
"image": "https://jdcivils.org/images/co.png",
"date": "28/Aug/2016",
"reply": [
{
"comment": "nahi",
"user": "Admin",
"image": "https://jdcivils.org/images/co.png",
"date": "28/Aug/2016"
}
]
}]
Try in this way
JSONArray jsonarray = new JSONArray(yourresponse))
for(int i=0;i<jsonarray.length;i++){
JSONObject jsonobject = jsonarray.getJsonObject(i);
String comment = jsonobject.getString("comment");
String user = jsonobject.getString("user");
String image = jsonobject.getString("image");
String date = jsonobject.getString("date");
JSONArray jsonarray1 = jsonobject.getJSONArray("reply");
for(int j=0; j<jsonarray1.length;j++){
String comment1 = jsonobject.getString("comment");
String user1 = jsonobject.getString("user");
String image1 = jsonobject.getString("image");
String date1 = jsonobject.getString("date");
}
}
I am assuming you are getting string in respose so convert it to jsonArray
JSONArray SamplejsonArray = new JSONArray(String);
for(int i = 0;i<SamplejsonArray .length();i++){
JSONObject SamplejsonObject = SamplejsonArray .getJsonObject(i);
String comment = SamplejsonObject .getString("comment");
String user = SamplejsonObject .getString("user");
String image= SamplejsonObject .getString("image");
String date= SamplejsonObject .getString("date");
JSONArray replyjsonArray = SamplejsonObject.getJSONArray(reply);
for(int j = 0;i<replyjsonArray .length();j++){
JSONObject replyjsonObject = replyjsonArray.getJsonObject(j);
String comment = replyjsonObject .getString("comment");
String user = replyjsonObject .getString("user");
String image= replyjsonObject .getString("image");
String date= replyjsonObject .getString("date");
}
}
Use json to pojo converter for create model class from complex json array
Refer link : http://www.jsonschema2pojo.org/
Use this library, all you need is create model with same key as string that you have. Gson parser
<Your model> value = new Gson().fromJson(new String(<Ur string>.getBytes("ISO-8859-1"),
"UTF-8"), <Your model>.class);
try this way
JSONArray jsonArray = new JSONArray(sampleString);
for(int i = 0;i<jsonArray.length();i++){
JSONObject jsonObject = jsonArray.getJsonObject(i)
String comment = jsonObject.getString("comment");
String user = jsonObject.getString("user");
JSONArray replyArray = jsonObject.getJSONArray("reply");
for(int j = 0;j<replyArray.length();j++){
JSONObject innerObject = replyArray.getJSONObject(j);
String comment = innerObject.getString("comment"); ...
}
}
try {
//Create array object from String object that contains your json array
JSONArray jArray = new JSONArray(jsonString);
//Get JSONObject from array
jArray.get(0);
} catch (JSONException e) {
e.printStackTrace();
}

Printing json object on an android textview

I have this json object as an output of a web service , I want to print each part_Name node on a separate android text view how to do that?
{
"0": [],
"1": {
"Part_ID": "1",
"Part_NAME": "part_name_one "
},
"2": {
"Part_ID": "2",
"Part_NAME": " part_name_two "
},
"3": {
"Part_ID": "3",
"Part_NAME": "part_name_three"
},
I tried this code but I don't get an output in my textview
jobj = jsonparser.makeHttpRequest("http://192.168.1.7:89/My_website/My_Webservice.php");
try {
JSONObject jsonRootObject = new JSONObject(jobj.toString());
JSONArray jsonArray = jsonRootObject.optJSONArray("Services_Parts");
for(int i=0; i < jsonArray.length(); i++){
JSONObject jsonObject = jsonArray.getJSONObject(i);
String name = jsonObject.optString("Part_NAME").toString();
data += "Node"+i+ "+ name +" +name+ " \n ";
tv2.setText(name);
}
if possible then try to change the structure of your json to something like that
[
{
"Part_ID": "1",
"Part_NAME": "part_name_one "
},
{
"Part_ID": "2",
"Part_NAME": " part_name_two "
},
{
"Part_ID": "3",
"Part_NAME": "part_name_three"
}
]
put each json object into an jsonarray .. as shown above
then parse each jsonobject and create the textview dynamically acc. to no. of jsonobject inside jsonarray
using the above ex. there are 3 jsonobject inside jsonarray
hence create 3 textview dynamically at the time of json parsing
JSONArray jsonArray = <your json array>;
for(int i=0; i < jsonArray.length(); i++){
JSONObject jsonObject = jsonArray.getJSONObject(i);
String name = jsonObject.optString("Part_NAME").toString();
addTextView(name);
}
// add text to dynamically created textview code..
public void addTextView(String text)
{
final TextView textView = new TextView(this);
textView.setText(text);
myLinearLayout.addView(textView);
}

Android parsing JSON with array in array

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

JSON parsing is it the right way of parsing data and image in listview

I am confused How to use looping for Json response Array in another Array. The following is my jsonresponse how to loop this to get data and images in listview
`{
"status": "ok",
"posts": [
{
"id": 2498,
"title": "jigsaw lamp imported from thailand",
"content": "<p>Hi. It’s a invitation to have a look at a unique lamp shade called jigsaw lamp from thailand. Available in multi attractive colours.</p>\n",
"date": "2012-12-26 09:48:15",
"author": {
"name": "Tapas123456",
},
"attachments": [
{
"description": "",
"caption": "",
"mime_type": "image/jpeg",
"images": {
"thumbnail": {
"url": "http://site/wp-content/uploads/2012/12/646675-50x47.jpg",
}
}
]
},........
the following is the code i used to loop is this the right way of doing it?
ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(URL);
try {
posts = json.getJSONArray(KEY_POSTS);
// looping through all song nodes <song>
for(int i = 0; i < posts.length(); i++){
JSONObject c = posts.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(KEY_ID);
String title = c.getString(KEY_TITLE);
String date = c.getString(KEY_DATE);
String content = c.getString(KEY_CONTENT);
// Phone number is agin JSON Object
JSONObject author = c.getJSONObject(KEY_AUTHOR);
String name = author.getString(KEY_NAME);
JSONArray attachments = json.getJSONArray(KEY_ATTACHMENTS);
for(int j = 0; j < attachments.length(); j++){
JSONObject d = attachments.getJSONObject(j);
JSONObject images = d.getJSONObject(KEY_IMAGES);
JSONObject thumbnail = d.getJSONObject(KEY_THUMB_URL);
String url = thumbnail.getString(KEY_URL);
}
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(KEY_ID, id);
map.put(KEY_TITLE, title);
map.put(KEY_DATE, date);
map.put(KEY_NAME, name);
map.put(KEY_CONTENT, content);
// adding HashList to ArrayList
songsList.add(map);
Just Replace Following code
for(int j = 0; j < attachments.length(); j++){
JSONObject d = attachments.getJSONObject(j);
JSONObject images = d.getJSONObject(KEY_IMAGES);
JSONObject thumbnail = images.getJSONObject(KEY_THUMB_URL);
String url = thumbnail.getString(KEY_URL);
}
instead of old code.

Categories

Resources