I have the following code in my main activity.
JSONObject jObj = new JSONObject(loadJSONFromAsset());
jObj.getJSONObject("body");
The contents of jObj looks like this:
{
"body" : {
"name" : {
"test" : "abc"
}
}
}
I can get the value of "body" by iterating "jObj.keys()", but how can I get the value of "name"?
Use this:
JSONObject jObj = new JSONObject(loadJSONFromAsset());
JSONObject objectName = jObj.getJSONObject("body").getJSONObject("name");
String test = objectName.getString("test"); //return abc
Try this..
JSONObject jObj = new JSONObject(loadJSONFromAsset());
JSONObject js = jObj.getJSONObject("body");
JSONObject jo = js.getJSONObject("name");
System.out.println("test value "+jo.getString("test");
Related
Asking after searching and trying many examples .
I'm trying to dynamically get list of values from json in order to insert into array .
The json looks like :
{
"Test_name":"mft",
"parameters":[
{
"Remotehost":"vl-tlv-ctm-qa22",
"Ftptype":"sftp",
"file_name":"blabla.txt"
}
]
}
i'm using the following code :
JSONParser parser = new JSONParser();
try {
Object obj = parser.parse(new FileReader("c:/temp/test.txt"));
JSONObject jsonObject = (JSONObject) obj;
String testname = (String) jsonObject.get("Test_name");
System.out.println(testname)
JSONArray msg = (JSONArray) jsonObject.get("parameters");
Iterator<JSONObject> iterator = msg.iterator();
while (iterator.hasNext()) {
JSONObject factObj = (JSONObject) iterator.next();
System.out.println(factObj);
the output is :
mft
{"Remotehost":"vl-tlv-ctm-qa22","file_name":"blabla.txt","Ftptype":"sftp"}
how do i break the pairs in the nested so i can use the as variables and not as single line ?
Thanks ,
Zohar
You can get the pairs as key-value pair from JSONObject as below:
while (iterator.hasNext()) {
JSONObject factObj = (JSONObject) iterator.next();
for (Object key : factObj.keySet()) {
System.out.println(key+":"+factObj.get(key));
}
}
When parsing some json like this:
{ "xxx_xxx" : "3424dfgdfg", "xxx_xxx_xxx" : "239923sdksd" }
I do it like this:
String respJSON = response.toString();
Object obj1 = parser.parse(respJSON);
JSONObject jsonObject = (JSONObject) obj1;
String xxxxxx = (String) jsonObject.get("xxx_xxx");
which works fine and gets the value of xxx_xxx perfectly.
but if the json looks like this:
{ "some" : { "something1" : "Nasdasdasd", "something2" : "232423423517",
but with a json respose like that how can I get into the second nesting if you know what I mean, so for example pulling out the value of "something1" because if I do it the same as the first I can only access "some" from that response?
Thanks.
You can extract JSONObject or JSONArray from a JSONObject :
With your exemple :
{ "some" : { "something1" : "Nasdasdasd", "something2" : "232423423517"}}
You can access something1 by doing :
String respJSON = response.toString();
Object obj1 = parser.parse(respJSON);
JSONObject jsonObject = (JSONObject) obj1;
JSONObject some = (JSONObject) jsonObject.getJSONObject("some");
String Nasdasdasd = (String) jsonObject.get("something1");
A JSONObject can contain other JSONObjects or Arrays.
jsonObject.getJSONObject("some");
I have a response like this:
{
"songs":{
"2562862600":{"id":"2562862600""pos":1},
"2562862620":{"id":"2562862620""pos":1},
"2562862604":{"id":"2562862604""pos":1},
"2573433638":{"id":"2573433638""pos":1}
}
}
Here is my code:
List<NameValuePair> param = new ArrayList<NameValuePair>();
JSONObject json = jParser.makeHttpRequest(url, "GET", param);
JSONObject songs= json.getJSONObject("songs");
How do I convert "songs" to a JSONArray?
Something like this:
JSONObject songs= json.getJSONObject("songs");
Iterator x = songs.keys();
JSONArray jsonArray = new JSONArray();
while (x.hasNext()){
String key = (String) x.next();
jsonArray.put(songs.get(key));
}
Even shorter and with json-functions:
JSONObject songsObject = json.getJSONObject("songs");
JSONArray songsArray = songsObject.toJSONArray(songsObject.names());
Your response should be something like this to be qualified as Json Array.
{
"songs":[
{"2562862600": {"id":"2562862600", "pos":1}},
{"2562862620": {"id":"2562862620", "pos":1}},
{"2562862604": {"id":"2562862604", "pos":1}},
{"2573433638": {"id":"2573433638", "pos":1}}
]
}
You can parse your response as follows
String resp = ...//String output from your source
JSONObject ob = new JSONObject(resp);
JSONArray arr = ob.getJSONArray("songs");
for(int i=0; i<arr.length(); i++){
JSONObject o = arr.getJSONObject(i);
System.out.println(o);
}
To deserialize the response need to use HashMap:
String resp = ...//String output from your source
Gson gson = new GsonBuilder().create();
gson.fromJson(resp,TheResponse.class);
class TheResponse{
HashMap<String,Song> songs;
}
class Song{
String id;
String pos;
}
JSONObject songs= json.getJSONObject("songs");
use JSONArray for direct conversion
JSONArray array = (JSONArray)songs.get("songs");
I am a beginner on JSON in Java http://json.org/java/
How can I create a JSON object like this?
{
"RECORD": {
"customer_name": "ABC",
"customer_type": "music"
}
}
Try like this:
JSONObject jsonObject = new JSONObject();
jsonObject.put("customer_name", "ABC");
jsonObject.put("customer_type", "music");
JSONObject jsonObject_rec = new JSONObject();
jsonObject_rec.put("RECORD", jsonObject);
System.out.println(jsonObject_rec);
You have to make "RECORD" an JSONobject. This is an example:
JSONObject json = new JSONObject();
// Add a JSON Object
JSONObject Record = new JSONObject();
Record.put( "customer_name", "ABC");
Record.put( "customer_type", "music");
json.put( "RECORD", Record);
// P toString()
System.out.println( "JSON: " + json.toString() );
I have a JSON Object that looks like this :
"TripList":{
"noNamespaceSchemaLocation":"http://api.vasttrafik.se/v1/hafasRestTrip.xsd",
"servertime":"11:27",
"serverdate":"2013-04-02",
"Trip":[{
"Leg":{
"name":"Spårvagn 3",
"type":"TRAM",
"id":"9015014500300079",
"direction":"Kålltorp",
"fgColor":"#004b85",
"bgColor":"#ffffff",
"stroke":"Solid",
"accessibility":"wheelChair",
"Origin":{
"name":"Brunnsparken, Göteborg",
"type":"ST",
"id":"9022014001760004",
"routeIdx":"19",
"time":"11:27",
"date":"2013-04-02",
"track":"D ",
"rtTime":"11:31",
"rtDate":"2013-04-02",
"$":"\n"
}
to get the name inside the Leg object is working fine.
But if I wanna get thetime inside the Origin object how do I do that?
My code is like this so far:
JSONParser parser = new JSONParser();
Object obj = parser.parse(Planner.getPlanner().getJsonDataForTrip(Planner.getPlanner().getStartLocationID(), Planner.getPlanner().getDestinationID()));
JSONObject topObject = (JSONObject) obj;
JSONObject locationList = (JSONObject) topObject.get("TripList");
JSONArray array = (JSONArray) locationList.get("Trip");
Iterator<JSONObject> iterator = array.iterator();
while (iterator.hasNext()) {
JSONObject jsonObj = iterator.next();
jsonObj = (JSONObject) jsonObj.get("Leg");
String line = (String) jsonObj.get("name");
Planner.getPlanner().setLines(line);
System.out.println(jsonObj.get("Origin"));
Long time = (Long) jsonObj.get("time");
String track =(String) jsonObj.get("track");
System.out.println(line);
System.out.println(time);
System.out.println(track);
}
}
And in the console it say like this :
{"routeIdx":"19","id":"9022014001760004","rtDate":"20130402","time":"15:02","$":"\n","name:"Brunnsparken, Göteborg","track":"D ","rtTime":"15:06","date":"2013-04-02","type":"ST"}
Spårvagn 3
null
null
So basiclly i am getting the name Spårvang 3 already. But I wanna get the time.
so the time that I am trying to get out by using jsonObj.get("time"); is giving a null value.
Whats the problem and how can I get the time from the object "Origin"??
Since "Time" is part of the "Origin"-object, you would need to extract the "Origin"-object first:
JSONOject origin = (JSONObject) jsonObj.get("Origin");
And then:
String time = origin.getString("time");
You are getting 'time' and 'track' properties of 'Leg' object, not the 'Origin' object..
It should be:
JSONParser parser = new JSONParser();
Object obj = parser.parse(Planner.getPlanner().getJsonDataForTrip(Planner.getPlanner().getStartLocationID(), Planner.getPlanner().getDestinationID()));
JSONObject topObject = (JSONObject) obj;
JSONObject locationList = (JSONObject) topObject.get("TripList");
JSONArray array = (JSONArray) locationList.get("Trip");
Iterator<JSONObject> iterator = array.iterator();
while (iterator.hasNext()) {
JSONObject jsonObj = iterator.next();
jsonObj = (JSONObject) jsonObj.get("Leg");
String line = (String) jsonObj.get("name");
Planner.getPlanner().setLines(line);
System.out.println(jsonObj.get("Origin"));
// Added this line
jsonObj = (JSONObject) jsonObj.get("Origin");
String time = (String) jsonObj.get("time");
String track =(String) jsonObj.get("track");
System.out.println(line);
System.out.println(time);
System.out.println(track);
}
Do following code
JSONOject origin = (JSONObject) jsonObj.get("Origin");
String time = (String) origin.getString("time");
them use SimpleDateFormat to parse time string and get date object