This question already has answers here:
How to parse JSON in Java
(36 answers)
Closed 7 years ago.
I have this format of code. Can anyone help me how can I read the array? I need to read contacts array.
{
"success": true,
"contacts": [
{
"username": "ceema",
"profile": {
"name": "Ceema S",
"email": "ceemas#gmail.com",
"address": "No 143, gangaeyam, Maikkad P O, Kerala",
"phone": {
"mobile": "3333",
"home": "2222",
"office": "6666"
}
}
},
{
"username": "hari",
"profile": {
"name": "Harikrishnan V S",
"email": "harikriii#gmail.com",
"address": "No 143, harihome, Maikkad P O, Kerala",
"phone": {
"mobile": "3333",
"home": "2222",
"office": "6666"
}
}
},
{
"username": "pranav",
"profile": {
"name": "Pranav Mohan",
"email": "pranavmohan#gmail.com",
"address": "No 143, harihome, Maikkad P O, Kerala",
"phone": {
"mobile": "3333",
"home": "2222",
"office": "6666"
}
}
}
]
}
I tried this :
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
contacts = jsonObj.getJSONArray(TAG_CONTACTS);
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
//String id = c.getString(TAG_NAME);
String name = c.getString(TAG_NAME);
String email = c.getString(TAG_EMAIL);
String address = c.getString(TAG_ADDRESS);
//String gender = c.getString(TAG_GENDER);
// Phone node is JSON Object
JSONObject phone = c.getJSONObject(TAG_PHONE);
String mobile = phone.getString(TAG_PHONE_MOBILE);
String home = phone.getString(TAG_PHONE_HOME);
String office = phone.getString(TAG_PHONE_OFFICE);
This jsonstr is json response from the site.
I need to read the nested contacts and populate it to
This jsonstr is json response from the site. I need to read the nested
contacts and populate it to
you got it almost right. The objects you are looking for are inside profile
JSONObject c = contacts.getJSONObject(i);
JSONObject profile = c.getJSONObject("profile");
and use profile instead of c, to look of name, phone and the others
check this link a very simple way to parse json
http://kylewbanks.com/blog/Tutorial-Android-Parsing-JSON-with-GSON
The simplest way is to get POJO class from json using http://www.jsonschema2pojo.org/
You will get all the required classes to convert this json into POJO class,
and later you can use Gson library from google to convert json into Object and the other way around.
Think of this, if you get a Contact class as parent class then you can easily use fromjson method from Gson.
Gson gson=new Gson();
Contact contact = gson.fromJson(json_string, Contact.class);
Now you can easily use this class for further use.
Hope this helps.
Related
I have a JSON Arrays of Array like this
"results": [
{
"id": "AAA",
"color": "#4D4837",
"links": {
"self": "https://aaa.com",
"html": "https://bbb.com",
"download": "https://ccc.com",
"download_location": "ddd.com"
},
"categories": [],
"likes": 3891,
},
{
"id": "BBB",
"color": "#4D453",
"links": {
"self": "https://abb.com",
"html": "https://bcc.com",
"download": "https://ccc.com",
"download_location": "ddd.com"
},
"categories": [],
"likes": 3000,
}
]
And I would like to retrieve "https://bbb.com" and "https://bcc.com" of "html", but I don't know how to do that.
Based on kindly comment, I put the following.
somehow, "getJSONObject()"can not be put. The error message says "Cannot resolve method 'getJSONObject' in 'JSONArray'".
JSONArray array = new JSONArray((Collection) jobjt.get("Strings"));
for (int i =0 ; i<2 ; i++){
JSONObject job = (JSONObject) array.get(i); --> get(i) can not be changed to getJSONObject(i)
String id = job.get("id").toString();
String color = job.get("color").toString();
String photoUrl = job.get("links").toString(); --> By updating here, I want to store only "https://bbb.com" and "https://bcc.com".
}
But when I tried to use the following, not only "html", but "self" and the other information are retrieved.
String photoUrl = job.get("links").toString();
Please tell me how to retrieve only "html".
I am using IntelliJ.
Steps to be followed(assuming you have proper JSONArray you mentioned):
get JSONObject from your JSONArray by index ie. for your case, index=0 here
Get the inner JSONObject by key of links
Now, access your content by key of html
Example for your case:
JSONObject indexedObject = jsonArray.getJSONObject(0);
JSONObject linksObject = indexedObject.getJSONObject("links");
String html= linksObject.getString("html");
Better keep checking if key exists as Harshal suggests
I am having trouble parsing a simple json in java. Here is the sample json.
[
{
"politics": [
{
"type": "admin2",
"friendly_type": "country",
"name": "United States",
"code": "usa"
},
{
"type": "admin6",
"friendly_type": "county",
"name": "Gratiot",
"code": "26_057"
},
{
"type": "constituency",
"friendly_type": "constituency",
"name": "Eighth district, MI",
"code": "26_08"
},
{
"type": "admin6",
"friendly_type": "county",
"name": "Clinton",
"code": "26_037"
},
{
"type": "admin4",
"friendly_type": "state",
"name": "Michigan",
"code": "us26"
},
{
"type": "constituency",
"friendly_type": "constituency",
"name": "Fourth district, MI",
"code": "26_04"
}
],
"location": {
"latitude": 43.111976,
"longitude": -84.71275
}
}
]
Now this gives me the correct json index.
JSONParser parser = new JSONParser();
Object obj = parser.parse(output);
JSONArray array = (JSONArray)obj;
String jsonobj = array.get(0).toString();
{"politics":[{"code":"usa","name":"United States","type":"admin2","friendly_type":"country"},{"code":"26_057","name":"Gratiot","type":"admin6","friendly_type":"county"},{"code":"26_08","name":"Eighth district, MI","type":"constituency","friendly_type":"constituency"},{"code":"26_037","name":"Clinton","type":"admin6","friendly_type":"county"},{"code":"us26","name":"Michigan","type":"admin4","friendly_type":"state"},{"code":"26_04","name":"Fourth district, MI","type":"constituency","friendly_type":"constituency"}],"location":{"latitude":43.111976,"longitude":-84.71275}}
But I cant seem to get the attribute that I want from it.
JSONObject obj1 = new JSONObject(jsonobj);
String n = obj1.getString("admin4");
System.out.println(n);
All that I need from this json is the state which is Michigan. Where am I wrong?
Help would be really appreciated.
First, array.get(0) will get you the first element from the main array. This first element is a JSON object that has two properties politics and location. You seem to be interested in a value that is inside the array value of the politics property. You'll have to use this ((JSONArray)((JSONObject)array.get(0)).get("politics")) to get that array.
Second, admin4 is not a property it is actually a value of the type property. You'll have to loop through the array to find it.
Here is a complete example:
JSONParser parser = new JSONParser();
Object obj = parser.parse(output);
JSONArray array = (JSONArray)obj;
JSONArray politics = ((JSONObject)array.get(0)).get("politics"));
JSONObject obj = null;
for(int i = 0; i < politics.size(); i++){
if(((JSONObject)politics.get(i)).getString("type").equals("admin4")){
obj = ((JSONObject)politics.get(i));
}
}
if(obj != null){
// Do something with the object.
}
It seems that you're using the simple json library. I don't remember exactly if it is .get("politics") or .getJSONObject("politics"). There may be other mistakes in method names in my example.
the best solution to simplify your search and other operations on json object, is the convert json string to java object and doing your operations.
for convert json string to java object use follow code:
import org.codehaus.jackson.map.ObjectMapper;
import org.json.JSONException;
import org.json.JSONObject;
YourObject myObject;
ObjectMapper mapper = new ObjectMapper();
try{
myObject= mapper.readValue(jsonData, myObject.class);
}
catch (Exception e) {
e.printStackTrace();
}
for example define your class ass follow :
public class myObject{
private List<Politics> politics;
private Location location;
// define getters and setters
}
define Politics and Location class:
public class Politics
{
String type;
String friendly_type;
String name;
String code;
// define getters and setters
}
public class Location
{
String latitude;
String longitude;
// define getters and setters
}
It's because your are trying to get the inner element of the JSON Object.
try
JSONObject obj1 = new JSONObject(jsonobj);
JSONArray arr = (JSONArray) obj1.getObject("politics");
You will get a JSONArray object which further constitutes of JSON objects.
Now in order to get values using the key you must iterate array as given below:
for(int i=0; i<arr.size(); i++){
JSONObject obj = arr.getJSONArray(i);
System.out.println(obj.getString("type"));
}
which will now provide you with output:
admin2
admin6
constituency
admin6
admin4
constituency
I have a JSON string and I am trying to retrieve information from it. Json String looks like this.
JSON STRING :
{
"information": {
"device": {
"id": 0
},
"user": {
"id": 0
},
"data": [
{
"datum": {
"id": "00GF001",
"history_id": "9992BH",
"name": "abc",
"marks": 57,
"class": "B",
"type": "Student"
}
},
{
"datum": {
"id": "72BA9585",
"history_id": "78NAH2",
"name": "ndnmanet",
"marks": 70,
"class": "B",
"type": "Student"
}
},
{
"datum": {
"id": "69AHH85",
"history_id": "NN00E3006",
"name": "kit",
"department": "EF003",
"class": "A",
"type": "Employee"
}
},
{
"datum": {
"id": "09HL543",
"history_id": "34QWFTA",
"name": "jeff",
"department": "BH004",
"class": "A1",
"type": "Employee_HR"
}
}
]
}
}
I am trying to access data JSONArray and respective Datum from it. I differentiated each datum as per type such as student, employee etc and push information in hashmap.
I successfully did it in javascript but in Java I am struggle abit.
When I am trying to access JSONArray it throws exception
try {
JSONObject data = new JSONObject(dataInfo);
// Log.d(TAG, "CHECK"+data.toString());
JSONObject info = data.optJSONObject("information");
if(info.getJSONArray("data").getString(0).equals("Student") > 0) //exception here
Log.d(TAG, "Data"+ data.getJSONArray("data").length()); //exception here too
for(int m = 0; m < data.length(); m++){
// for(int s = 0; s < data[m].ge)
}
} catch (JSONException j){
j.printStackTrace();
}
Any pointers to create hashmap respective type I have. Appreciated
If you're trying to access the type field of a datum object, you'll want something like this:
JSONObject data = new JSONObject(dataInfo); // get the entire JSON into an object
JSONObject info = data.getJSONObject("information"); // get the 'information' object
JSONArray dataArray = info.getJSONArray("data"); // get the 'data' array
for (int i = 0; i < dataArray.length(); i++) {
// foreach element in the 'data' array
JSONObject dataObj = dataArray.getJSONObject(i); // get the object from the array
JSONObject datum = dataObj.getJSONObject("datum"); // get the 'datum' object
String type = datum.getString("type"); // get the 'type' string
if ("Student".equals(type)) {
// do your processing for 'Student' here
}
}
Note that you'll have to deal with exception handling, bad data, etc. This code just shows you the basics of how to get at the data that you're looking for. I separated each individual step into its own line of code so that I could clearly comment what is happening at each step, but you could combine some of the steps into a single line of code if that is easier for you.
if dataInfo is the json you posted, then you have to access information and from information, you can access data:
JSONObject data = new JSONObject(dataInfo);
JSONObject info = data.optJSONObject("information");
if (info != null) {
JSONArray dataArray = info.optJSONArray("data")
}
In my android project, I have the string text which got the following data:
[
{
"admin": true,
"created_at": "2012-10-16T07:26:49Z",
"email": "asdf#gmail.com",
"id": 28,
"language": "fr",
"name": "Marc",
"profile_pic_content_type": null,
"profile_pic_file_name": null,
"profile_pic_file_size": null,
"profile_pic_updated_at": null,
"provider": null
},
{
"admin": false,
"created_at": "2013-04-02T18:47:36Z",
"email": "asdf2#gmail.com",
"id": 263,
"language": "en",
"name": "Marcus",
"profile_pic_content_type": null,
"profile_pic_file_name": null,
"profile_pic_file_size": null,
"profile_pic_updated_at": null,
"provider": null
}
]
I converted it into a json object thanks to this:
JSONObject jsonObj = new JSONObject(text);
I want to parse that Json object, and setting it inside a ListView, but even with the official documentation I can't succeed in doing so.
After parsing, I want to keep only the first part of the array, and delete every field excepting the email, language and name, to get this in the end:
[
{
"email": "asdf#gmail.com",
"language": "fr",
"name": "Marc"
}
]
You're dealing with a JSONArray - the [ ] - that contains two separate JSONObject. The way you extract values from this structure is simply to go piece by piece, first getting the nested objects from the array and then extracting their internal values. You can then repackage it as you wish. For example:
int numObject = jsonArray.length();
JSONArray repackArray = new JSONArray();
for(int i = 0; i < numObject; i++){
JSONObject nested = jsonArray.getJsonObject(i);
//get values you need
String email = nested.getString("email");
String language = nested.getString("language");
String name = nested.getString("name");
//add values to new object
JSONObject repack = new JSONObject();
repack.put("email", email);
repack.put("language", language);
repack.name("name", name);
//add to new array
repackArray.put(repack);
}
Alternatively if put doesn't work for you, you can always create your own String in JSON format and then simply create a new JSONObject using that string as an argument in the constructor. I assumed you were working with a JSONArray in the above example. If you're starting with a JSONObject the process is the same. Just get the JSONArray out of the object first before unpacking.
I am new to JSON. I'm working with the json processing library. Given a JSON such as:
{
"data": [
{
"name": "John Doe",
"id": "2980311"
},
{
"name": "Jane Doe",
"id": "10221412"
},
{
"name": "George Doe",
"id": "111623489"
}
],
"paging": {
"blah" : "blah"
}
}
How can I get the id values. I've started by trying to get an array to work with:
String URL = "https://graph.facebook.com/username/friends?access_token=";
String token = "";
String[] response = loadStrings(URL+token);
if(response != null) {
JSONObject result = new JSONObject(response);
JSONArray data = result.getJSONArray("data");
}
And this prints out:
JSONObject["data"] not found.
JSONObject["data"] is not a JSONArray.
But it's definitely getting the data. If I print out response I see the data.
What am I missing?
I'm not seeing a JSONObject constructor in that library that accepts String[] (the type of your response variable). There's JSONObject(String) and there's JSONObject(Object). If you pass a String[] into JSONObject, it'll match the latter, which doesn't (immediately) look to me like it'll do what you want.
I suspect you want to get a single String from the URL, which you'd then pass into JSONObject(String), at which point things should start working correctly.
try with this..
GraphObject responseGraphObject = response.getGraphObject();
JSONObject json = responseGraphObject.getInnerJSONObject();
JSONObject sys = json.getJSONObject("data");
Log.e("urlimage json", sys.getString("url"));