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)
Answer from kiruwka on Stack OverflowHi, I'm stuck on json file. How do I data from json file?
Below example, I would like to extract 1.["name" of "user"], 2.["name" of "user" in reply_status], 3.["text" in "reply_status"]
There are other data as well.
Should I use loop?
{
"replyed_date":"Wed Dec 17",
"id":545025256960,
"id_str":"5450256960",
"text":"hello world",
"user":{
"id":275881,
"id_str":"275881",
"name":"Json",
},
"reply_status":{
"created":"Wed Dec 16",
"id":545020558720,
"id_str":"545058558720",
"text":"Hello world",
"user":{
"id":874136,
"id_str":"874136",
"name":"Farmony",
"screen_name":"Fiftony",
}
}
}
{.......
}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.
Since it's not so clear what you've tried, you might look into things like
JACKSON -- a JSON parsing/generation system.
Or a whole host of other utilities.
Writing your own parser would be a waste of time.
Reading from the file may or may not be covered by the utilities, but you can handle that--or there may be some utility in Apache Commons.
Jackson Reference
Here is an example of how to read data using Jackson JSON library:
// create Jackson mapper
ObjectMapper mapper = new ObjectMapper();
String inputString = "{json goes here...}";
// parse JSON into JsonNode, now you can navigate the data structure
JsonNode json = mapper.readTree(inputString);
// get node
JsonNode searchResultsNode = json.get("searchResults");
// get another node from that node
JsonNode classifiedAdvertsNode = searchResultsNode.get("classifiedAdverts");
// get it's value as string
String someValue = classifiedAdvertsNode.asText();
If you need to read a file, just pass the file into mapper.readTree(inputString), it will work just as well.
see this code what i am used in my application
String data="{'foo':'bar','coolness':2.0, 'altitude':39000, 'pilot':{'firstName':'Buzz','lastName':'Aldrin'}, 'mission':'apollo 11'}";
I retrieved like this
JSONObject json = (JSONObject) JSONSerializer.toJSON(data);
double coolness = json.getDouble( "coolness" );
int altitude = json.getInt( "altitude" );
JSONObject pilot = json.getJSONObject("pilot");
String firstName = pilot.getString("firstName");
String lastName = pilot.getString("lastName");
System.out.println( "Coolness: " + coolness );
System.out.println( "Altitude: " + altitude );
System.out.println( "Pilot: " + lastName );
Pasting my code here, this should help. It shows the package which can be used.
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\"}}";
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);
}
}
You can use Gson library for this.
String json="{MsgType:AB,TID:1,ItemID:34532136,TransactTime:1389260033223}";
Map jsonJavaRootObject = new Gson().fromJson(json, Map.class);
System.out.println(jsonJavaRootObject.get("MsgType"));
where the jsonJavaRootObject will contain a map of keyvalues like this
{MsgType=AB, TID=1.0, ItemID=3.4532136E7, TransactTime=1.389260033223E12}
I use JSONObject under android but from Oracle docs I see its also available under javax.json package:
http://docs.oracle.com/javaee/7/api/javax/json/package-summary.html
If you want Gson then your code should look like below (sorry not compiled/tested):
/*
{"MsgType":"AB","TID":"1","ItemID":"34532136","TransactTime":1389260033223}
*/
Gson gson = new Gson();
static class Data{
String MsgType;
String TID;
String ItemID;
int TransactTime;
}
Data data = gson.fromJson(yourJsonString, Data.class);
So I have this JSON data given by this link http://api.openweathermap.org/data/2.5/forecast/daily?q=94043&mode=json&units=metric&cnt=7
I'm trying to make a method which can find the maximum temperature on a certain day which would be proved as a parameter.
What is the best way to do this?
The code I have so far is this:
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class WeatherDataParser {
/**
* Given a string of the form returned by the api call:
* http://api.openweathermap.org/data/2.5/forecast/daily?q=94043&mode=json&units=metric&cnt=7
* retrieve the maximum temperature for the day indicated by dayIndex
* (Note: 0-indexed, so 0 would refer to the first day).
*/
public static double getMaxTemperatureForDay(String weatherJsonStr, int dayIndex)
throws JSONException {
// TODO: add parsing code here
JSONObject object = new JSONObject(weatherJsonStr);
double max = object.getDouble("max");
return max;
}
} I know this code doesn't include dayIndex yet but I was just trying to get the code to be able to recognise where to find the max temperature before I changed it to take into account the day also.
This isn't homework, I'm just trying to learn android development in my own time.
String jsonString = yourstring;
JSONObject jsonResult = new JSONObject(jsonString);
JSONArray data = jsonResult.getJSONArray("data");
if(data != null) {
String[] names = new String[data.length()];
String[] birthdays = new String[data.length()];
for(int i = 0 ; i < data.length() ; i++) {
birthdays[i] = data.getString("birthday");
names[i] = data.getString("name");
}
}
check http://www.androidhive.info/2012/01/android-json-parsing-tutorial/
Edit your code like this ...this may help you..
JSONObject resultObject = new JSONObject(response);
JSONArray JArray = resultObject.getJSONArray("data");
for (int t=0; t<JArray.length(); t++) {
JSONObject JObject = JtArray.getJSONObject(t);
builder.append(JObject.getString("uid")+": ");