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
Related
This is my json from the code below:
"ict":[
{
"module1":{
"1":[
"OS",
"Operating system"
],
"2":[
"CA",
"Computer Application"
],
"3":[
"CM",
"Computational Mathematics"
],
"4":[
"CA",
"Computer Application"
],
"5":[
"Programming",
"Structured Programming"
]
},
I want to access this part
"1":["OS","Operating system"]
but get the string "OS" without fetching the whole string.
When I run my java code which is this:
private void addItemsFromJSON() {
try {
JSONObject jsonObject = new JSONObject(readJSONDataFromFile());
JSONArray coursea = jsonObject.getJSONArray("ict");
for (int i = 0; i < coursea.length(); i++) {
JSONObject cc = coursea.getJSONObject(i);
JSONObject contact = cc.getJSONObject("module1");
courses.add(new course(contact.getString("1"),"",String.valueOf(content.get(ran.nextInt(content.size())))));
}
} catch (JSONException | IOException e) {
Log.d(TAG, "addItemsFromJSON: 777", e);
}
}
The output that I get is ["OS", "Operating system"]
How can I retrieve only the first object from a json key array with multiple values?
The data at "1" refers to another JSONArray, so to get the first item in the array you would do something like this:
JSONArray array = contact.getJSONArray("1");
array.getString(0);
In JSON objects are denoted using {} and arrays with []. If you're trying to access a specific value in your JSON object then it's really just a case of following the path to it, through the arrays and objects.
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")
}
Need your expert advise here. So I have a complex JSON string that has multiple Java objects. Here is my JSON string. I have only listed one java object but it has plenty (each mapped to a java class in my code)
{
"myStoreInfo": {
"id": "12370034",
"address": australia,
"partnerInfo": {
"retailPartner": false
},
"customerContactInfo": {
"name": {
"firstName": "Ricky",
"middleName": "Sage",
"lastName": "Higging",
"gender": "Male",
},
"customerPhone": {
"areaCode": "",
"extension": "",
"completeNumber": "1234567",
},
"contactEmail": {
"emailAddress": "ricky#gmail.com"
}
}
}
}
I basically need to validate a few elements in the entire JSON string to make sure they are not null. Here is the code for validation -
public static String validateJSON(String jsonFile, Object objToValidate) throws JSONException {
JSONObject myStoreInfo = jsonFileObj.getJSONObject("myStoreInfo");
JSONObject jsonObj = null;
if(myStoreInfo!=null) {
if(myStoreInfo.isNull("id"))
return "myStoreInfo info id is null";
if(myStoreInfo.isNull("address"))
return "myStoreInfo address field is null";
jsonObj = myStoreInfo.getJSONObject("partnerInfo");
if(jsonObj!=null) {
if(jsonObj.isNull("retailPartner"))
return "partner info retail partner is null";
}
jsonObj = myStoreInfo.getJSONObject("customerContactInfo");
JSONObject name = jsonObj.getJSONObject("name");
if(name!=null) {
if(name.isNull("firstName"))
return "myStoreInfo first name is null";
if(name.isNull("lastName"))
return "myStoreInfo last name is null";
}
jsonObj = myStoreInfo.getJSONObject("customerContactInfo");
jsonObj = jsonObj.getJSONObject("contactEmail");
if(jsonObj==null)
return "myStoreInfo email id is null";
}
return null;
}
}
This works well if I am doing the validation for one java object, and my json file has that java object only. But the fact is my json file has too many of these strings that internally map to various java objects. My question here is - I need to be able to pass these objects to validate them individually. As you can see here, my validateJSON takes the object to pass as an argument. How do I split the JSON string for each object, and validate all the fields within that object are fine?
As you have too many arrays in that json string converting to Java Array list might be easier
JSONArray jsonArray = new JSONArray(jsonFile);
for(int i = 0; i < jsonArray.length(); i++){
JSONObject json = (JSONObject)new JSONParser().parse(jsonArray[i]);
//convert to java list
}
I know its an array, but I am completely new to JSON and need help comprehending how this is structured, here is my attempt at extracting data:
String JSonString = readURL("//my URL is here");
JSONArray s = JSONArray.fromObject(JSonString);
JSONObject Data =(JSONObject)(s.getJSONObject(0));
System.out.println(Data.get("name"));
My JSON data that I have goes like this :
{
"sports": [
{
"name": "basketball",
"id": 40,
"uid": "s:40",
"leagues": [
{
"name": "National Basketball Assoc.",
"abbreviation": "nba",
"id": 46,
"uid": "s:40~l:46",
"groupId": 7,
"shortName": "NBA",
"athletes": []
}
]
}
],
"resultsOffset": 10,
"resultsLimit": 10,
"resultsCount": 1,
"timestamp": "2013-11-18T03:15:43Z",
"status": "success"
}
I dont really have a strong grasp of this stuff so all the help is appreciated.
Here is the idea :
JSONObject root = new JSONObject(yourJsonString);
JSONArray sportsArray = root.getJSONArray("sports");
// now get the first element:
JSONObject firstSport = sportsArray.getJSONObject(0);
// and details of the first element
String name = firstSport.getString("name"); // basketball
int id = firstSport.getInt("id"); // 40
JSONArray leaguesArray = firstSport.getJSONArray("leagues");
// and so on, you can process leaguesArray similarly
It should work (feel free to complain about compile errors if there are any)
Your JSON data is an object (it starts with a curly brace). In the next inner layer, there is a single array (at key "sports"):
String jsonString = readURL("//my URL is here");
JSONObject result = JSONObject(jsonString);
JSONArray sports = result.getJSONArray("sports");
JSONObject sport = sport.getJSONObject(0);
System.out.println(sport.getString("name"));
I might have used another JSON library than you.
JSON means JavaScript Object Notation.
Objects in javascripts are just containers and can be represented by key-value pairs. Please find below notations to understand about json.
Represent objects in json: E.g. Student
{"name" : "Robin", "rollnumber" : "1"}
Represent array in json : E.g. Array of students
[{"name" : "Robin", "rollnumber" : "1"}, {"name" : "Mark", "rollnumber" : "2"}]
You can understand more on JSON from diagrams on this link http://www.json.org/fatfree.html
There are various ways available to to convert JSON to javaobject and javaobject to JSON : One of them is http://wiki.fasterxml.com/JacksonInFiveMinutes
Adding detailed code here along with the imports .
If this helps.
import org.json.JSONException;
import org.json.JSONObject;
public class extractingJSON {
public static void main(String[] args) throws JSONException {
// TODO Auto-generated method stub
String jsonStr = "{\"name\":\"SK\",\"arr\":{\"a\":\"1\",\"b\":\"2\"},\"arrArray\":[{\"a\":\"1\",\"b\":\"2\"}]}";
JSONObject jsonObj = new JSONObject(jsonStr);
String name = jsonObj.getString("name");
System.out.println(name);
String first = jsonObj.getJSONObject("arr").getString("a");
System.out.println(first);
first = jsonObj.getJSONArray("arrArray").getJSONObject(0).getString("a");
System.out.println(first);
}
}
so, there's this JSON code. Im trying to get the "abridged_cast".
but its complicated.
its JSONObject
inside JSONArray onside jSONObject Inside JsonArray....
{
"total": 591,
"movies": [
{
"title": "Jack and Jill",
"year": 2011,
"runtime": "",
"release_dates": {
"theater": "2011-11-11"
},
"ratings": {
"critics_score": -1,
"audience_score": 90
},
"synopsis": "",
"posters": {
"thumbnail": "",
"profile": "",
"detailed": "",
"original": ""
},
"abridged_cast": [
{
"name": "Al Pacino",
"characters": []
},
{
"name": "Adam Sandler",
"characters": []
},
{
"name": "Katie Holmes",
"characters": []
}
],
"links": {
"self": "",
"alternate": ""
}
}
],
"links": {
"self": "",
"next": ""
},
"link_template": ""
}
this is my code for getting "title" and "year"
if (response != null) {
try {
// convert the String response to a JSON object,
// because JSON is the response format Rotten Tomatoes uses
JSONObject jsonResponse = new JSONObject(response);
// fetch the array of movies in the response
JSONArray movies = jsonResponse.getJSONArray("movies");
// add each movie's title to an array
movieTitles = new String[movies.length()];
for (int i = 0; i < movies.length(); i++) {
JSONObject movie = movies.getJSONObject(i);
movieTitles[i] = movie.getString("title");
}
hope someone would help me because i cant figure out how to get the abridged_cast"
movies contains an array of "movie" objects. Each one of those objects contains a field abridged_cast that is an array of (let's call them "cast member") objects.
If you're not going to map to a POJO and instead are going through the JSON, you simply need to get that array in your loop after getting movie, and get each "cast member" object from that array in the same manner using another loop.
...
JSONArray cast = movie.getJSONArray("abridged_cast");
for (int j = 0; j < cast.length(); j++) {
JSONObject castMember = cast.getJSONObject(j);
...
}
Edit from comments: Your original question involved how to extract the information from the JSON you have; the above code explains that. It now seems like you're asking a more fundamental programming question around how to use it.
If you're going to use the included org.json classes that come with Android, you now know how to access the information in the returned JSON object. And you could write methods around the parsed JSONObject to access the data as-is using the objects and methods from the json.org package. For example, you could write a "getMovie()" method that took the name of the movie as a string and searched that "movies" array for the right one and returned it as a JSONObject.
Normally you would create classes in Java that encapsulate the data returned in that JSON and use data structures that lend themselves to your access patterns (For example, a Map that conatained all the movies using their names as keys). Using the org.json classes you'll have to instantiate those objects and populate them manually as you parse the JSON like you're doing in your question. If you used either the Gson or Jackson JSON parsing libraries they are capable of taking the JSON you have and mapping all the data to the classes your create and returning them in a single call.
try {
String Movie = null;
String abridged = null;
JSONArray jsonResponse = new JSONArray(response);
for (int i = 0; i< jsonResponse.length(); i++) {
Movie = jsonResponse.getJSONObject(i).getString("movies").toString();
System.out.println("movies="+Movie);
abridged = jsonResponse.getJSONObject(i).getString("abridged_cast").toString();
}
JSONArray jArray = new JSONArray(Movie);
for (int i = 0; i< jArray.length(); i++) {
String title = jArray.getJSONObject(i).getString("title").toString();
System.out.println("title="+title);
}
JSONArray jabridgeArray = new JSONArray(abridged);
for (int i = 0; i< jabridgeArray.length(); i++) {
String title = jabridgeArray.getJSONObject(i).getString("name").toString();
System.out.println("title="+title);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}