JSONObject parse dictionary objects - java

JSON values that I get from server:
{
"Status":0,
"Message":"",
"Result":{"0B":"S.C. Blue Air","0Y":"FlyYeti","1X":"Branson Air"}
}
Getting the result as 'response' after connection and I am able to show my JSON string results on the screen.
JSONObject json = new JSONObject(response);
String status = json.getString("Status");
String message = json.getString("Message");
String result = json.getString("Result");
responseView.setText("Status" + status+ "Message" + message" + Result" + result);
I am okay the results of "Status" and "Message" but not with "Result" because want to separate "Result" objects as and able use each of them as objects.
For example:
When I type OB in my app, I will get the result S.C. Blue Air

Instead of :
String result = json.getString("Result");
use
if(json.get("Result") instanceof JSONObject){
JSONObject object = (JSONObject) json.get("Result");
//do what you want with JSONObject
String ob = object.get("0B");
}
If you want to store it some way you can put it to Map or create object if always it is same data

You can use some libraries such as Gson (Google) or Moshi (Square)
Those libraries allows you to declare your model as a plain java class (commonly called POJOS) annotated in some way that this libraries bind your properties in the JSON to your java properties.
In your case:
JSON:
{
"Status":0,
"Message":"",
"Result":{"0B":"S.C. Blue Air","0Y":"FlyYeti","1X":"Branson Air"}
}
MODEL:
public class MyCallResponse {
#SerializedName("Status")
int status;
#SerializedName("Message")
String message;
#SerializedName("Result")
Result result;
}
public class Result {
#SerializedName("0B")
String b;
#SerializedName("0Y")
String y;
#SerializedName("0X")
String x;
}
In this case, with Gson you can do:
MyCallResponse response = new Gson().fromJson(json, MyCallResponse.class);
Log.i("Response b", response.result.b);
Look at the documentation for more information about both libraries.

try this :
JSONObject json = new JSONObject(response);
JSONObject resultObj = json.getJSONObject("Result");
String OB = resultObj.getString("OB");

Try this
String base = ""; //Your json string;
JSONObject json = new JSONObject(base);
JSONOBject resultJson = json.getJSONObject("Result");
// Get all json keys "OB", "OY", "1X" etc in Result, so that we can get values against each key.
Set<Map.Entry<String, JsonElement>> entrySet = resultJson.entrySet();
Iterator iterator = entrySet.iterator();
for (int j = 0; j < entrySet.size(); j++) {
String key = null; //key = "OB", "OY", "1X" etc
try {
Map.Entry entry = (Map.Entry) iterator.next ();
key = entry.getKey ().toString ();
//key = "OB", "OY", "1X" etc
}
catch (NoSuchElementException e) {
e.printStackTrace ();
}
if (!TextUtils.isEmpty (key)) {
Log.d ("JSON_KEY", key);
String value = resultJson.getString(key);
//for key = "0B", value = "S.C. Blue Air"
//for key = "0Y", value = "FlyYeti"
//for key = "1X", value = "Branson Air"
}
}
It works with any array with dynamic json key.
Don't forget to accept the answer & upvote if it works.

Related

How to get dynamically changed Key's value in Json String using java

I'm trying to parse Json string using java, I have stuck up with some scenario.
See below is my JSON String:
"NetworkSettings": {
"Ports": {
"8080/tcp": [ // It will change dynamically like ("8125/udp" and "8080/udp" etc....)
{
"HostIp": "0.0.0.0",
"HostPort": "8080"
}
]
}
}
I try to parse the above json string by using the following code:
JsonObject NetworkSettings_obj=(JsonObject)obj.get("NetworkSettings");
if(NetworkSettings_obj.has("Ports"))
{
JsonObject ntw_Ports_obj=(JsonObject)NetworkSettings_obj.get("Ports");
if(ntw_Ports_obj.has("8080/tcp"))
{
JsonArray arr_ntwtcp=(JsonArray)ntw_Ports_obj.get("8080/tcp");
JsonObject ntwtcp_obj=arr_ntwtcp.get(0).getAsJsonObject();
if(ntwtcp_obj.has("HostIp"))
{
ntw_HostIp=ntwtcp_obj.get("HostIp").toString();
System.out.println("Network HostIp = "+ntw_HostIp);
}
if(ntwtcp_obj.has("HostPort"))
{
ntw_HostPort=ntwtcp_obj.get("HostPort").toString();
System.out.println("Network HostPort = "+ntw_HostPort);
}
}
else
{
ntw_HostIp="NA";
ntw_HostPort="NA";
}
}
else
{
ntw_HostIp="NA";
ntw_HostPort="NA";
}
In my code I have used this code
JsonArray arr_ntwtcp=(JsonArray)ntw_Ports_obj.get("8080/tcp");
to get the value of "8080/tcp"
How can I get the values of dynamically changing key like ("8125/udp","8134/udp", etc...)
Note: I'm using gson library for parsing
After modification
public static void main(String args[])
{
try
{
JsonParser parser = new JsonParser();
JsonObject obj=(JsonObject)parser.parse(new FileReader("sampleJson.txt"));
System.out.println("obj = "+obj);
JsonObject NetworkSettings_obj=(JsonObject)obj.get("NetworkSettings");
if(NetworkSettings_obj.has("Ports"))
{
JsonObject ntw_Ports_obj=(JsonObject)NetworkSettings_obj.get("Ports");
System.out.println("ntw_Ports_obj = "+ntw_Ports_obj);
Object keyObjects = new Gson().fromJson(ntw_Ports_obj, Object.class);
List keys = new ArrayList();
System.out.println(keyObjects instanceof Map); //**** here the statement prints false
if (keyObjects instanceof Map) // *** so controls doesn't enters into the if() condition block *** //
{
Map map = (Map) keyObjects;
System.out.println("Map = "+map);
keys.addAll(map.keySet());
String key = (String) keys.get(0);
JsonArray jArray = (JsonArray) ntw_Ports_obj.get(key);
System.out.println("Array List = "+jArray);
}
}
}
catch(Exception e)
{
}
}
You can do something like that (not tested but should be ok) :
if (ntw_Ports_obj.isJsonArray()) {
Iterator it = ntw_Ports_obj.getAsJsonArray().iterator();
while (it.hasNext()) {
JsonElement element = (JsonElement) it.next();
if(element.isJsonArray()){
JsonArray currentArray = element.getAsJsonArray();
// Do something with the new JsonArray...
}
}
}
So your problem is the key 8080/tcp is not fixed and it may change. when this situation you can try like this to get the value of the Dynamic key.
Set<Map.Entry<String, JsonElement>> entrySet = ntw_Ports_obj
.entrySet();
for (Map.Entry<String, JsonElement> entry : entrySet) {
String key = entry.getKey();
JsonArray jArray = (JsonArray) ntw_Ports_obj.get(key);
System.out.println(jArray);
}
Edit:
Object keyObjects = new Gson().fromJson(ntw_Ports_obj, Object.class);
List keys = new ArrayList();
/** for the given json there is a one json object within the 'Ports' so the 'keyObjects' will be the 'Map'**/
if (keyObjects instanceof Map) {
Map map = (Map) keyObjects;
keys.addAll(map.keySet());
/**
* keys is a List it may contain more than 1 value, but for the given
* json it will contain only one value
**/
String key = (String) keys.get(0);
JsonArray jArray = (JsonArray) ntw_Ports_obj.get(key);
System.out.println(jArray);
}

How to retrieve JSON object inside another JSON object?

Guyz I am beginner in android. My question is how to get json object which is inside object. For example As shown in my below JSON data which I got from google places api, how to get open_now object which is inside opening_hours ?
"opening_hours" : {
"open_now" : true,
"weekday_text" : []
}
Below is my java code:
// Check for all possible status
if(status.equals("OK")){
// Successfully got places details
if (nearPlaces.results != null) {
// loop through each place
for (Place p : nearPlaces.results) {
HashMap<String, String> map = new HashMap<String, String>();
double rate=p.rating;
boolean ostatus=p.open_now;
String rvalue = String.valueOf(rate);
//Log.d("Rating",rvalue );
double latitude = p.geometry.location.lat;
double longitude = p.geometry.location.lng;
Location selected_location=new Location("locationA");
selected_location.setLatitude(userlat);
selected_location.setLongitude(userlng);
Location near_locations=new Location("locationA");
near_locations.setLatitude(latitude);
near_locations.setLongitude(longitude);
double distance=selected_location.distanceTo(near_locations);
double dvalue=(Math.round(distance));
String dsvalue = String.valueOf(dvalue);
// Log.d("distance", dvalue);
// Place reference won't display in listview - it will be hidden
// Place reference is used to get "place full details"
map.put(KEY_REFERENCE, p.reference);
// Place name
map.put(KEY_NAME, p.name);
map.put(KEY_EXTRA,rvalue);
int price= p.price_level;
String pc = String.valueOf(price);
String plevel="Inexpensive";
if(pc.equals("0")){
plevel= "Inexpensive";
}
else if(pc.equals("1")){
plevel= "Inexpensive";
}
else if(pc.equals("2")){
plevel= "Moderate";
}
else if(pc.equals("3")){
plevel= "Expensive";
}
else if(pc.equals("4")){
plevel= "Very Expensive";
}
map.put(KEY_PLEVEL,plevel);
String add=p.vicinity;
map.put(KEY_ADD, add);
System.out.println("open status"+String.valueOf(ostatus));
// Log.d("Status",ostatus);
String tstat;
if(ostatus==false){
tstat="Open";
}
else{
tstat="Open";
}
map.put(KEY_STAT, tstat);
// Log.d("price level",price);
map.put(KEY_DISTANCE, dsvalue+" M");
placesListItems.add(map);
}
You should use JSONObject:
JSONObject json = new JSONObject(data);
try{
JSONObject openingHours = json.getJSONObject("opening_hours");
boolean openNow = openingHours.getBoolean("open_now");
}catch(JSONException e){
e.printStackTrace();
}
You can read more about JSONObject here.
you have an Array in your JSONObject not an JSONObject, your model should be like this :
Class Item {
ArrayList<String> weekday_text;
boolean open_now;
}
now try to parse this model.
...
// reader contains your json String that comes from server
Gson gson = new GsonBuilder().create();
Item item = gson.fromJson(reader, Item.class);
// now use your item object

JSON Parsing in Java Webservice of multiple JSONObjects in JSONObject

This is my JSON string,
{
"listmain":{
"16":[{"brandid":"186"},{"brandid":"146"},{"brandid":"15"}],
"17":[{"brandid":"1"}],
"18":[{"brandid":"12"},{"brandid":"186"}],
}
}
I need to get values in "16","17","18" tag and add values and ids("16","17","18") to two ArrayList.
What i meant is,
when we take "16", the following process should happen,
List<String> lsubid = new ArrayList<String>();
List<String> lbrandid = new ArrayList<String>();
for(int i=0;i<number of elements in "16";i++) {
lsubid.add("16");
lbrandid.add("ith value in tag "16" ");
}
finally the values in lsubid will be---> [16,16,16]
the values in lbrandid will be---> [186,146,15]
Can anyone please help me to complete this.
Use JSONObject keys() to get the key and then iterate each key to get to the dynamic value.
You can parse the JSON like this
JSONObject responseDataObj = new JSONObject(responseData);
JSONObject listMainObj = responseDataObj.getJSONObject("listmain");
Iterator keys = listMainObj.keys();
while(keys.hasNext()) {
// loop to get the dynamic key
String currentDynamicKey = (String)keys.next();
//store key in an arraylist which is 16,17,...
// get the value of the dynamic key
JSONArray currentDynamicValue = listMainObj.getJSONArray(currentDynamicKey);
int jsonrraySize = currentDynamicValue.length();
if(jsonrraySize > 0) {
for (int i = 0; i < jsonrraySize; i++) {
JSONObject brandidObj = currentDynamicValue.getJSONObject(i);
String brandid = brandidObj.getString("brandid");
System.out.print("Brandid = " + brandid);
//store brandid in an arraylist
}
}
}
Source of this answer

How to get specific JSON data?

Hi I am trying to read JSON from an ReST API but Im getting a nullpointer exception because mycode is not correct.
I have a JSON that I am reading from looking like this :
processJSON({
"LocationList":{
"noNamespaceSchemaLocation":"http://api.vasttrafik.se/v1/hafasRestLocation.xsd",
"servertime":"16:13",
"serverdate":"2013-03-22",
"StopLocation":[{
"name":"Brunnsparken, Göteborg",
"lon":"11.967824",
"lat":"57.706944",
"id":"9021014001760000",
"idx":"1"
},{
"name":"Brunnsgatan, Göteborg",
"lon":"11.959455",
"lat":"57.693766",
"id":"9021014001745000",
"idx":"4"
},{
"name":"Brunnslyckan, Lerum",
"lon":"12.410219",
"lat":"57.812073",
"id":"9021014017260000",
"idx":"5"
},
Now I want the name from the JSON document depending on what the user inputs.
how do I do this with code?
My code that is wrong is like this :
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
public class JSONReader {
private String jsonData = "";
public String getJsonData(String location){
try {
URL url = new URL("http://api.vasttrafik.se/bin/rest.exe/v1/location.name?authKey=secret&format=json&jsonpCallback=processJSON&input=" + URLEncoder.encode(location, "UTF-8"));
URLConnection connection = url.openConnection();
BufferedReader readJsonFile = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
String temp = "";
while((temp = readJsonFile.readLine()) != null){
jsonData += temp;
}
readJsonFile.close();
System.out.println(jsonData);
return jsonData;
}
catch (IOException e) {
}
return null;
}
public void JSONParsing(){
String location = Planner.getPlanner().getStartingLocation();
JSONObject obj =(JSONObject)JSONValue.parse(getJsonData(location));
//Set the text into the JList
if (obj.containsValue(location));
obj.get("name");
}
}
I want get the same name of the location out from the JSON as the user inputs.
How do I do this with code?
I think that you are asking how to parse your JSONObject and get the corresponding values out of it that the user is interested in. Below is an example of how you can pull apart the JSONObject to create a Map whose key is the String id (since the name does not seem to be unique) and whose value is the whole JSONObject. You can use this map to lookup the input from the user and find the appropriate LLA if that's what you are interested in.
public Map<String, JSONObject> createLocationMap(JSONObject jsonObj){
Map<String, JSONObject> nameToLocationMap = new HashMap<String, JSONObject>();
JSONObject locationList = (JSONObject) jsonObj.get("LocationList");
JSONArray array = (JSONArray) locationList.get("StopLocation");
for (int i = 0; i < array.length(); i++) {
String name = (String) ((JSONObject) array.get(i)).get("id");
nameToLocationMap.put(name, ((JSONObject)array.get(i)));
}
return nameToLocationMap;
}
You can tailor this method as you see fit. For example if you are interested in the relationship between the id and the name then you can create a similar method that uses those values instead of id and the entire JSONObject'. I hope that this helps~

How to parse a JSONArray of JSONObjects in JAVA?

I have the following array returned to my JAVA Android application from PHP:
Array ( [0] => Array ( [referral_fullname] => Name 1 [referral_balance] => 500 ) [1] => Array ( [referral_fullname] => Name 2 [referral_balance] => 500 ) );
In Java they above array looks like this:
{"0":{"referral_fullname":"Name 1","referral_balance":"500"},"1":{"referral_fullname":"Name 2","referral_balance":"500"}};
For a simple JSONObject I'm using:
JSONTokener tokener = new JSONTokener(result.toString());
JSONObject finalResult = new JSONObject(tokener);
referral_fullname = finalResult.getString("referral_fullname");
but for an array of objects I don't know!
String str = your Json-> apply to.String();
JSONObject jObject = new JSONObject(str);
Map<String,String> map = new HashMap<String,String>();
Iterator iter = jObject.keys();
while(iter.hasNext()){
String key = (String)iter.next();
String value = jObject .getString(key);
map.put(key,value);
}
Your Json Syntax is wrong , JSONArray should be like this :
["0":{"referral_fullname":"Name 1","referral_balance":"500"},"1":{"referral_fullname":"Name 2","referral_balance":"500"}];
and to parse a JsonArray that contains some JSONObject , try this :
//parse the result
JSONObject jsonResult = null;
JSONArray arrayResult = null;
ArrayList<YourObject> listObjects = null;
try {
arrayResult = new JSONArray(result);
if(arrayResult != null) {
listObjects = new ArrayList<YourObject>();
int lenght = arrayResult.length();
for(int i=0; i< lenght; i++) {
JSONObject obj = arrayResult.getJSONObject(i);
YourObject object = new YourObject(obj);
listObjects.add(object);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
And add a constructor in your Class YourObject to convert your Json to an instance :
public YourObject(JSONObject json) {
if (!json.isNull("referral_fullname"))
this.referral_fullname = json.optString("referral_fullname", null);
if (!json.isNull("referral_balance"))
this.referral_balance = json.optString("referral_balance", null);
}
You should use
JSONArray finalResult = new JSONArray(tokener);
if you can. You structure is now an object with two fields, 0 and 1, which contains another object. You have to get an array of object in place of this composite object if you want to iterate easily like
JSONObject jso;
for(int i = finalResult.lenght-1; i >=0; i--){
jso = finalResult.get(i);
// jso == {"referral_fullname":"Name 1","referral_balance":"500"}
[whatever]
}
Try this.............
final JSONArray result_array = json.getJSONArray("result");
for (int i = 0; i < result.length(); i++) {
JSONObject joObject = result_array.getJSONObject(i);
String jName = joObject.get("referral_fullname").toString();
String jbalance = joObject.get("referral_balance").toString();
}
First make an JSON object and see then in inner level what you have if you have array then fetch array.
You need to make JSON object first. For example, if resp is a String (for example coming as http response)
JSONObject jsonObject = new JSONObject(resp);
jsonObject may contains other JSON Objects or JSON array. How to convert the JSON depends on the response.
If arraykey is a array inside the JSON objects then we can get list of array by the following way.
JSONArray arr = jsonObject.getJSONArray("arraykey");
Check the length of arr, if it is greater than 0 then it contains JSON objects or JSON array depending the data.
There is a complete example with some explanation about JSON String to JSON array can be found at
http://www.hemelix.com/JSONHandling

Categories