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);
}
}
Related
I have a string like below
{
"id": "abc",
"title": "123.png",
"description": "fruits",
"information": [
{
"type": "apple",
"url": "https://apple.com"
},
{
"type": "orange",
"url": "https://orange.com"
}
],
"versions": 0
}
I want to get the value of url where type: orange. The list in information may not always be in same order as appearing in the data above. I know I could do it easily in python with json.loads and json.dump.
I am trying to do it java using JsonNode and objectMapper.readTree.at("/information") but I am unable to get past this point in a clever neat way to get the list and fetch the url where type = orange.
This is pretty straightforward
Use a JSON library and parse the response using the library. Then get only the values and attributes that you need...
Example relevant to your case:
// Get your Json and transform it into a JSONObject
JSONObject mainObject = new JSONObject(yourJsonString); // Here is your JSON...
// Get your "information" array
JSONArray infoArray = mainObject.getJSONArray("information"); // Here you have the array
// Now you can go through each item of the array till you find the one you need
for(int i = 0 ; i < infoArray.length(); i++)
{
JSONObject item = participantsArray.getJSONObject(i);
final String type = item.getString("type");
final String url = item.getString("url");
if(type.equals("orange"))
{
// DO WHATEVER YOU NEED
}
}
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 json file in below format.
{
"data":[
{
"prjId": 1,
"name" : "Forj1",
"issue": [
{
"id": 00001,
"status" : "Closed"
},
{
"id": 00002,
"status" : "Open"
}
]
},
{
"prjId": 2,
"name" : "Forj2",
"issue": [
{
"id": 00003,
"status" : "Closed"
},
{
"id": 00004,
"status" : "Open"
}
]
}],
"issueCounter": 7,
"success": true
}
Here "data" is array of projects, and within project attribute there is array of "issue".
So far if I remove "issue" array, I am able to traverse the json to one level down in "data" attribute, If this json has "issue" array I get an error saying missing comma.
javax.json.stream.JsonParsingException: Invalid token=NUMBER at (line no=15, column no=14, offset=242) Expected tokens are: [COMMA]
Below is the code that I have right now. I have two problems with this, one is the error while reading if I place the "issue" attribute, and secondly a way to read the "issue" array and traverse all attributes within.
InputStream fis = new FileInputStream(pathToFile+"data3.json");
JsonReader jsonReader = Json.createReader(fis);
//the error is thrown on below line while reading the above json.
JsonObject jsonObject = jsonReader.readObject();
jsonReader.close();
fis.close();
System.out.println(jsonObject.getInt("issueCounter"));
//reading arrays from json
JsonArray jsonArrayData = jsonObject.getJsonArray("data");
Project [] prj = new Project[jsonArrayData.size()];
int index = 0;
for(JsonValue value : jsonArrayData){
JSONObject jsonObj = new JSONObject(value.toString());
System.out.println(jsonObj.getString("name"));
System.out.println(jsonObj.getInt("prjId"));
//this is also the place where I am stuck, I know I need to construct an array out of it by obtaining issue attribute. Below is very very wrong.
/*
JsonArray jsonArrayIssue = jsonObj.getJsonArray("issue");
for(JsonValue issue : jsonArrayIssue){
JSONObject jsonIssueObj = new JSONObject(issue.toString());
System.out.println(jsonIssueObj.getString("status"));
System.out.println(jsonIssueObj.getInt("id"));
}
*/
}
Any help or pointers is deeply appreciated. I can tweak the json if its required ultimately I need to maintain an array of issues.
The problem as others said is the JSON.
"id": 00001 <-- this is a number, numbers cannot start with a leading zero as per JSON stadard.
If you control the JSON you should tweak it.
Alternatively ff you don't, you can use a less strict parser like org.json.simple https://mvnrepository.com/artifact/com.googlecode.json-simple/json-simple
The code will be the same as yours, just adjusted to org.json.simple
try { ...
JSONObject rootJSON = (JSONObject) new JSONParser().parse(jsonString);
JSONArray dataList = (JSONArray) rootJSON.get("data");
for(Object projectObj: dataList.toArray()){
JSONObject project = (JSONObject)projectObj;
JSONArray issueList = (JSONArray) project.get("issue");
for(Object issueObj: issueList.toArray()){
JSONObject issue = (JSONObject) issueObj;
//do something with the issue
}
}
} catch (ParseException e) {
//do smth
e.printStackTrace();
}
Your json data is invalid.You can check here.
http://jsonlint.com
...issue": [{ "id": 00001,
"status": ----------------------^
Your id must be string number,string,boolean.Send 1,2,3,.... as return values and check if it works.
Your code looks okay the problem is the JSON formatting. Specifically the following lines:
"id": 00001,
"id": 00002,
"id": 00003,
"id": 00004,
Basically if you want it in that format you will need to set them as strings by wrapping the values in quotations i.e. "id": "00001" or you can use a valid number i.e. "id": 1
Currently working on an android app and I need help on how I can go about extracting the subfields within the responses field of this json object:
Currently I am doing the following to extract some of the other fields:
JSONObject json = new JSONObject(response2);
int id = json.getInt("id");
String desc = json.getString("description");
JSONObject json2 = json.getJSONObject("owner");
String username = json2.getString("userName");
You need to create logic to parse the data. Every item from the JSON string is in the JSONObject you created with
JSONObject json = new JSONObject(response2);
You're on the right track with what you're doing. Just use the corresponding methods available in JSONObject and JSONArray classes to move through the object.
Start with the main object
{ // <-- this is your main object (AKA JSONObject json = new JSONObject(response2))
"id": 1, // to pull this id use json.getInt("id");
"title": "some text here", // to pull this title use json.getString("title");
...
"owner": { // Here's the logic part, owner is itself, a JSON object. so now you must extract it and parse through it.
// to pull the "owner" JSON object, use JSONObject ownerObject = json.getJSONObject("owner");
"userId": 1, // Now use the ownerObject to pull it's values. ownerObject.getInt("userId");
"userName": "TestingUser", // to pull this userName use ownerObject.getString("userName");
...
}
...
}
If it's an array, for example:
"someJSONArray": [{ "id": 1, "userName": "TestingUser1" }, { "id": 2, "userName": "TestingUser2" }]
then you would call:
JSONArray someJSONArray = getJSONArray("someJSONArray");
// Get each object from the array.
JSONObject object1 = someJSONArray.getJSONObject(0);
JSONObject object2 = someJSONArray.getJSONObject(1);
or if the array contains a string, for example:
"someKey": [ 23, 435, 123, 6345, 123 ]
then you would call:
JSONArray someKeyArray = getJSONArray("someKey");
for (int i = 0; i < someKeyArray.length(); i++) {
// Extract the value.
int itemValue = someKeyArray.getInt(i);
}
The data is there, you just have to parse it.
I'm trying to grab the 'name' from the JSON snippet I've included. I have tried the following but what I'm expecting is never grabbed.
Edit: 'output' is the full JSON string in case it wasn't already understood ;)
JSONObject result = null;
JSONArray data = null;
try {
try {result = new JSONObject(output);} catch (JSONException e) {e.printStackTrace();}
try {
data = result.getJSONArray("data");
for(int a=0;a<data.length();a++){
System.out.println(result.getJSONObject(String.valueOf(a)).getString("name"));//getJSONObject("results")
}
Here is the JSON snippet I'm trying to work with:
{
"code": 200,
"status": "Ok",
"copyright": "© 2015 MARVEL",
"attributionText": "Data provided by Marvel. © 2015 MARVEL",
"attributionHTML": "Data provided by Marvel. © 2015 MARVEL",
"etag": "b130a8b7af591e4e7ca078753f9c5c8a76e55e5d",
"data": {
"offset": 0,
"limit": 20,
"total": 1485,
"count": 20,
"results": [
{
"id": 1011334,
"name": "3-D Man",
"description": "",
"modified": "2014
.
.
.
.
.
.
.
.
.
.
To get you started, "data" points to a JSON Object, not array. So it should be:
data = result.getJSONObject("data");
Then, "results" points to a JSON array:
JSONArray results = data.getJSONArray("results");
Then you can try your loop. You shouldn't be turning a into a String - getJSONObject() takes an int for the index.
In case you're confused between Objects and Arrays, a JSON object has key - value pairs and are enclosed in curly braces. The keys are strings and the values can be a mix of any type:
{"key1": 5, "key2": "value2", "key3": {
"anotherObject": [1,2,3,4]
}
}
An array is a list of objects and is enclosed in square brackets:
[{...}, {...}, {...}]
The elements in the list don't have to be JSON objects, and in good JSON they will all be of the same type:
[1,2,3,4,4] or ["we", "are", "in", "an", "array"]
JSONTokener jsonTokener = new JSONTokener(jsonVaule);
JSONObject jsonObject = (JSONObject) jsonTokener.nextValue();
Int code =jsonObject.getInt("code");
String status =jsonObject.getString("status");
//{obejcet,obejcet,...}
for data{} is the same way~
JSONObject dataJsObject = (JSONObject) jsonObject.getJsonObject("data");
int offset =dataJsObject.getInt(""iffset);
....
//[{},{}] this type is jsonArrary
JSONArray results = dataJsObject.getJSONArray("results");
for(JSONObject resultJsonObj:JSONArray){
Int id =jsonObject.getInt("id");
//...and so on
}
hope it can help you~
You can parse like that
JsonObject obj = new JsonObject(StringResponse);
String code = obj.getString(code);
//same way you can get other string
JsonObject obj1 = obj.getJsonObject(Data);
String offset= obj.getString(offset);
//same way you can get other string
JsonArray jsonarr = obj1.getJsonArray(results);
for(i=0;i< jsonarr.size(); i++){
JsonObject innerObj = jsorr.getJsonObject(i);
String id= obj.getString(id);
//same way you can get other string
}
Hope It will helpful for you