Android: get child of Object [duplicate] - android

This question already has answers here:
How to parse JSON in Java
(36 answers)
Closed 4 years ago.
My code is :
Object value = tasks.get(key);
result value is : [{"name":"one","family":"yes"},{"name":"two","family":"no"}]
Now i want get child of value in foreach
foreach(...){
String name = ...
String family = ...
}

Your value is in JSONArray format.
Use this:
JSONArray values = new JSONArray((String) tasks.get(key)); // or alternative task.getString(key)
for (int i = 0; i < values.length(); i++) {
JSONObject entry = values.getJSONObject(i);
String name = entry.getString("name");
String family = entry.getString("family");
}

Step 1: Convert Object instance into String
String response = (String) value;
Step 2: Feed the String instance into JsonArray
//don't forget to caught JSONException here
JsonArray array = new JsonArray(response);
Step 3:
Iterate through JsonArray and get values from each JsonObject
for (int i = 0; i < array.length(); i++) {
JSONObject object = array.getJSONObject(i);
//get values here
String name = object.getString("name");
String family = object.getString("family");
}
Now, the whole code should look like this
try {
JSONArray array = new JSONArray("");
for (int i = 0; i < array.length(); i++) {
JSONObject object = array.getJSONObject(i);
String name = object.getString("name");
String family = object.getString("family");
}
} catch (JSONExceptione) {
//do something..
}
Important
If you still don't know what happened, this whole process is called JSON parsing. Learn about it.

Object itself not containig fields or something, you have to create pojo (just if you want clean and resuseble code) in order to get fields from it, for example, using Gson
Add dependencies:
dependencies {
implementation 'com.google.code.gson:gson:2.8.5'
}
Add pojo:
public class Pojo{
#SerializedName("name")
#Expose
private String name;
#SerializedName("family")
#Expose
private String family;
}
Convert:
Gson gson = new Gson();
Pojo pojo = gson.fromJson(jsonObject.toString(), Pojo.class);

Related

Why I am getting null JSON response?

I am fetching data from JSON to android.But, I am getting an empty JSON response. The PHP code which generates JSON data is as follows:
$result = $conn->query("SELECT dbname FROM users ORDER BY dbname ASC");
//defined second array for dbnames' list
$dblist = array();
while($row = $result->fetch_assoc()){
//array_push($response['dblist'],$row['dbname']);
$dblist[] = array('name'=>$row['dbname']);
}
$response['dblist'] = $dblist;
This is the JSON response.
{"dblist":[{"name":"a"},{"name":"arsod"}]}
The Java code to fetch data in android is as follows:
JSONObject obj = new JSONObject(s);
JSONArray names = obj.getJSONArray("dblist");
for(int i=0; i < names.length(); i++) {
JSONObject n = names.getJSONObject(i);
String name = n.getString("name");
Toast.makeText(MainActivity.this, name, Toast.LENGTH_SHORT).show();
institutes.add(name);
}
where institutes is an ArrayList in which I want to add each fetched element. But while fetching the data, I get the error in logcat org.json.JSONException: End of input at character 0 of. What is going wrong?
Considering the following:
s = {"dblist":[{"name":"a"},{"name":"arsod"}]}
Your code should be like,
JSONObject obj = new JSONObject(s);
JSONArray names = obj.getJSONArray("dblist");
for(int i=0; i < names.length(); i++) {
JSONObject n = names.getJSONObject(i);
String name = n.getString("name");
Toast.makeText(MainActivity.this, name, Toast.LENGTH_SHORT).show();
institutes.add(name);
}
remove this line:
JSONObject object = obj.getJSONObject("dblist");
and replace all occurences of object. with obj.
your JSONObject obj doesn't contain "dblist" object, there is only array inside it, so you should look for getJSONArray("dblist") straight inside obj
edit: you are parsing different String s, I've just checked this code:
final String s = "{\"dblist\":[{\"name\":\"a\"},{\"name\":\"arsod\"}]}";
JSONObject obj = new JSONObject(s);
JSONArray names = obj.getJSONArray("dblist");
for (int i = 0; i < names.length(); i++) {
JSONObject n = names.getJSONObject(i);
String name = n.getString("name");
Toast.makeText(this, name, Toast.LENGTH_SHORT).show();
}
which is almost exacly same as your and works pretty fine...

I am facing some problems with json parsing

{"success":"true",
"groups":[
{
"groupId":"c20f2353-1f13-4ea0-8283-ghhjc4dcc725251b",
"name":"hb",
"description":"hjj",
"image":null,
"membersCount":1,
"groupType":"chaddt",
"productCategeory":"bdfjgh",
"members":[
{
"memberId":"0031ea31-a71c-49f8ddbff6-8adaa310db02",
"memberName":"ddddsnta",
"contactId":"5a303564dd-2349-4cca-a190-f36f28ff54cb",
"contactName":"dssnta",
"role":"member"
}
],
}
]
}
This is my json.I am having some difficulty in parsing this.I am trying this solution.please suggest some ideas how to parse this type of json.Thanks for your answer
JSONArray jsonArray = jsonObject.getJSONArray("groups");
for (int i = 0; i < jsonArray.length(); i++) {
groupid = jsonArray.getJSONObject(i).getString("groupId");
String name = jsonArray.getJSONObject(i).getString("name");
String description =jsonArray.getJSONObject(i).getString("description");
String membersCount = jsonArray.getJSONObject(i).getString("membersCount");
String intrested = jsonArray.getJSONObject(i).getString("productCategeory");
JSONArray memberJsonArray = jsonArray.getJSONObject(i).getJSONArray("members");
for (int j = 0; j < memberJsonArray.length(); j++) {
String memberNamename = memberJsonArray.getJSONObject(j).getString("contactName");
String contactId = memberJsonArray.getJSONObject(j).getString("contactId");
String role = memberJsonArray.getJSONObject(j).getString("role");
GroupsDto groupDtoData = new GroupsDto();
groupDtoData.setGroupName(name);
groupDtoData.setGroupServerId(groupid);
System.out.println("groupid"+groupid);
groupDtoData.setGroupDescription(description);
groupDtoData.setProductCategory(intrested);
System.out.println("descr"+intrested);
groupDtoData.setGetmemberCount(membersCount);
groupDtoData.setGroupmembername(memberNamename);
System.out.println("membernames"+memberNamename);
groupDto.add(groupDtoData);
db.addGroups(groupDtoData);
}
This is my json.I am having some difficulty in parsing this.I am trying this solution.please suggest some ideas how to parse this type of json.Thanks for your answer
Your JSON response does not have any array name.
Instead of this :
JSONArray jsonArray = jsonObject.getJSONArray("groups");
Use This:
JSONArray jsonArray = jsonObject.getJSONArray(yourResponseStringHere);
It just needed to use Gson library and create corresponding class with your json file.
Gson : https://github.com/google/gson
Check this answer .It may help you fixing this.
JsonArray jarray=response.getJsonArray("groups");
for(int i=0;i<jarray.length();i++)
{
JsonObject jobj=jarray.getJsonObject(i);
String groupId=jobj.optString("groupId");
//do like this for all
//to get members
JsonArray jarray2=jobj.getJsonArray("members");
for(int j=0;j<jarray2.length();j++)
{
JsonObject jobj2=jarray2.getJsonObject(j);
String memberId=jobj2.optString("memberId");
//do this for all
}
}

How to split this kind of data in android

Here is the
string one =[{"ID":5,"Name":"Sai"}]
how i get only id and name from this string
Matcher matcher = Pattern.compile("\\[([^\\]]+)").matcher(one);
List<String> tags = new ArrayList<String>();
int pos = -1;
while (matcher.find(pos+1)){
pos = matcher.start();
tags.add(matcher.group(1));
}
System.out.println("getting data"+tags);
i tried this but it didn't work
List<String> ls = new ArrayList<String>(one);
JSONArray array = new JSONArray();
for(int i = 0; i< array.length(); i++){
JSONObject obj = array.getJSONObject(i);
ls.add(obj.getString("Name"));
}
It's JSON format and it can very easily be read in Android. Here is the sample code:
JSONArray array = new JSONArray(one);
int length = array.length();
for(int i=0;i< length; i++)
{
JSONObject temp = array.getJSONObject(i);
System.out.println(temp.getString("ID"));
System.out.println(temp.getString("Name"));
}
This format of data is called JSON.
Have a look at Go to http://json.org/, scroll to (almost) the end, click on one of the many Java libraries listed.
First of all, your string initialization is wrong.
Wrong:
string one =[{"ID":5,"Name":"Sai"}]
Correct:
String one ="[{\"ID\":5,\"Name\":\"Sai\"}]";
Second, its a JSON formatted data so you can parse it using JSONArray and JSONObject classes, instead of creating any pattern.
Now, in your case its JSONObject inside JSONArray so initially create an object of JSONArray using your string.
For example:
JSONArray arrayJSON = new JSONArray(one); // 'one' is your JSON String
for(int i=0; i<arrayJSON.length(); i++) {
JSONObject objJson = arrayJSON.getJSONObject(i);
String ID = objJson.getString("ID");
.....
.....
// same way you can fetch/parse any string/value from JSONObject/JSONArray
}
it is a json formate Date
use JsonObject class to parse this data
tutorial this
JSONArray jsonArray = new JSONArray("[{\"ID\":5,\"Name\":\"Sai\"}]");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject object = jsonArray.getJSONObject(i);
System.out.println(object.getString("ID"));
System.out.println(object.getString("Name"));
}

How to parse JSON without title object in Android?

I've a json output which returns something like this :
[
{
"title":"facebook",
"description":"social networking website",
"url":"http://www.facebook.com"
},
{
"title":"WoW",
"description":"game",
"url":"http://us.battle.net/wow/"
},
{
"title":"google",
"description":"search engine",
"url":"http://www.google.com"
}
]
I am familiar with parsing json having the title object, but i've no clue about how to parse the above json as it is missing the title object. Can you please provide me with some hints/examples so i can check them and work on parsing the above code?
Note : I've checked a similar example here but it doesn't have a satisfactory solution.
Your JSON is an array of objects.
The whole idea around Gson (and other JSON serialization/deserialization) libraries is that you wind up with your own POJOs in the end.
Here's how to create a POJO that represents the object contained in the array and get a List of them from that JSON:
public class App
{
public static void main( String[] args )
{
String json = "[{\"title\":\"facebook\",\"description\":\"social networking website\"," +
"\"url\":\"http://www.facebook.com\"},{\"title\":\"WoW\",\"description\":\"game\"," +
"\"url\":\"http://us.battle.net/wow/\"},{\"title\":\"google\",\"description\":\"search engine\"," +
"\"url\":\"http://www.google.com\"}]";
// The next 3 lines are all that is required to parse your JSON
// into a List of your POJO
Gson gson = new Gson();
Type type = new TypeToken<List<WebsiteInfo>>(){}.getType();
List<WebsiteInfo> list = gson.fromJson(json, type);
// Show that you have the contents as expected.
for (WebsiteInfo i : list)
{
System.out.println(i.title + " : " + i.description);
}
}
}
// Simple POJO just for demonstration. Normally
// these would be private with getters/setters
class WebsiteInfo
{
String title;
String description;
String url;
}
Output:
facebook : social networking website
WoW : game
google : search engine
Edit to add: Because the JSON is an array of things, the use of the TypeToken is required to get to a List because generics are involved. You could actually do the following without it:
WebsiteInfo[] array = new Gson().fromJson(json, WebsiteInfo[].class);
You now have an array of your WebsiteInfo objects from one line of code. That being said, using a generic Collection or List as demonstrated is far more flexible and generally recommended.
You can read more about this in the Gson users guide
JSONArray jsonArr = new JSONArray(jsonResponse);
for(int i=0;i<jsonArr.length();i++){
JSONObject e = jsonArr.getJSONObject(i);
String title = e.getString("title");
}
use JSONObject.has(String name) to check an key name exist in current json or not for example
JSONArray jsonArray = new JSONArray("json String");
for(int i = 0 ; i < jsonArray.length() ; i++) {
JSONObject jsonobj = jsonArray.getJSONObject(i);
String title ="";
if(jsonobj.has("title")){ // check if title exist in JSONObject
String title = jsonobj.getString("title"); // get title
}
else{
title="default value here";
}
}
JSONArray array = new JSONArray(yourJson);
for(int i = 0 ; i < array.lengh(); i++) {
JSONObject product = (JSONObject) array.get(i);
.....
}

how to be easier to analyse the json

i want to analyse the json just like:
[{"id":"ssq","name":"双色球","term":"2010092","date":"2010-08-12 19:15","numbers":{"normal":"3,13,19,27,28,30","special":"2"},"jackpot":"30000000"},{"id":"3d","name":"3D","term":"2010216","date":"2010-08-12 19:55","numbers":{"normal":"6,8,8"},"jackpot":"-"},{"id":"qlc","name":"七乐彩","term":"2010093","date":"2010-08-11 20:45","numbers":{"normal":"08,09,10,11,16,21,27","special":"26"},"jackpot":"0"},{"id":"dfljy","name":"东方6+1","term":"2010093","date":"2010-08-14 18:30","numbers":{"normal":"4,1,3,9,7,2","special":"羊"},"jackpot":"12866531"},{"id":"swxw","name":"15选5","term":"2010217","date":"2010-08-12 18:45","numbers":{"normal":"1,3,5,13,15"},"jackpot":"5693612"},{"id":"ssl","name":"时时乐","term":"20100811-23","date":"2010-08-12 10:27","numbers":{"normal":"6,7,1"},"jackpot":"-"},{"id":"klsf","name":"快乐十分","term":"201021649","date":"2010-08-11 22:00","numbers":{"normal":"5,11,12,14,20"},"jackpot":"-"},{"id":"klsc","name":"快乐双彩","term":"2010215","date":"2010-08-10 21:25","numbers":{"normal":"12,23,10,15,7,3","special":"11"} ,"jackpot":"198059"}]
i want to gain all of them,but the data is so many,so whether i need to create 8 kinds of class to store the data,so to be easier to use.thanks!
To add to cfei's response, one thing that I've done when processing JSON responses from Flickr, is create a new class particularly for that type of object.
So for yours, just playing it by ear, something like the below:
public class Lottery() {
private JSONObject json;
private String id;
private String name;
private String term;
private String date;
private String norm_numbers;
private String spec_numbers;
private String jackpot;
public Lottery(JSONObject json) {
this.json = json;
}
public void setId()
{
try {
id = json.getString("id");
} catch (JSONException e) {
id = "";
}
}
//additional getters and setters, etc.
}
This way, you can make an array of objects, and access the fields like so:
//...get a JSONObject from the array...
Lottery lottery = new Lottery(json);
Log.v("ID", lottery.id);
Log.v("Name", lottery.name);
and so on.
Do you mean that you want to iterate through each of the eight JSONObjects in this JSONArray? You need to create a JSONArray object with the input string you posed above (let's call it "response", as used below) and then iterate through the array to get each JSONObject it contains. For example:
JSONArray array = new JSONArray(response);
for(int i = 0; i < array.length(); i++) {
JSONObject obj = array.getJSONObject(i);
// do something with obj
// example: to get the id for a particular object, use obj.getString("id")
Log.i("Example", "the id is"+obj.getString("id"));
}

Categories

Resources