java- How to take out json data from string - java

this is my json string for example :
{"data":{ "name":"Red Sox win 7-0!","famil":"INSERT TITLE HERE","tel":"2251472"}}
this is the code I write but it couldn't get the values:
JSONObject jsons = new JSONObject(myString);
Iterator<?> keys = jsons.keys();
String out = "";
while (keys.hasNext()) {
String key = (String) keys.next();
out += key + ": " + jsons.getString(key) + "\n";
}
How can I get each item's value ?

try this code.
JSONObject object = new JSONObject(myString);
JSONObject objectData = object.getJSONObject("data");
String strTel = objectData .optString("tel");
String strFamil = objectData .optString("famil");
String strName = objectData .optString("name");

In your case you can use jsons.getString(key) for each key because your JSONObject contains only Strings.
But in general, JSONObject can contain values of different types: integer, boolean, int/long, double JSONArray and JSONObject. You have to use the right .getSomething() for each one or generat .get() that retuns Object.

Great example json-simple-example-read-and-write-json

Related

how to update json array in java with existing json array value using java. Value are not updating in external json file

JSON file:
[
{
"name":"John",
"city":"Berlin",
"job":"Teacher"
},
{
"name":"Mark",
"city":"Oslo",
"job":"Doctor"
}
]
JSONParser parser = new JSONParser();
JSONArray a = (JSONArray) parser.parse(new FileReader("F:\file.json"));
for (Object o : a) {
JSONObject person = (JSONObject) o;
String name = (String) person.get("name");
if (name.equalsIgnoreCase("john")) {
String name1 = (String) person.get("name");
System.out.println("name1" + name1);
String city1 = (String) person.get("city");
System.out.println("city1" + city1);
String job1 = (String) person.get("job");
System.out.println("job1" + job1);
person.put("city", "BLR");
String city2 = (String) person.get("city");
System.out.println("city2" + city2);
}
}
Value are not updating in Json external file
JSONObject is a represent of json that does not link to originally file.
To rewrite file you need to change values in person and write it to file.
person.put("city", "BLR");
String jsonString = person.toString();
// write jsonString to file

How to sum up two json values in java android?

Can any one tell me, how to sum two JSON objects values? Say, for an example:
First JSON
{
"json_obj":20,
}
Second JSON
{
"json_obj":40,
}
Here what I wanted is, I'm trying to create one JSON as same as like the above one, but i need to sum up two values of the JSON object "json_obj" and finally need to show it as like the below JSON
Resultant JSON
{
"json_obj":60
}
How to achieve this?
Try this,
JSONObject jsonObject1 = new JSONObject(First_JSON);
JSONObject jsonObject2 = new JSONObject(Socond_JSON);
JSONObject jsonObject3 = new JSONObject();
jsonObject3.put("json_obj", jsonObject1.getInt("json_obj")+jsonObject2.getInt("json_obj"));
Try this:
public String getAddedValues(String firstJson, String secondJson, String key){
JSONObject first = new JSONObject(firstJson);
JSONObject second = new JSONObject(secondJson);
int value = first.getInt(key) + second.getInt(key);
JSONObject output = new JSONObject();
output.put(key, value);
return output.toString();
}
Invoke it passing your json Strings and the "json_obj" String as key.
The idea is that you forst need to convert the json string into a Java object. Then you do your calculations, and finally you create another JSONObject with the result. JSONObject.toString() returns the common String representation you would expect as output :-)
You can try something like that:
public class CalcObj {
public int json_obj;
}
public String sumTwoJsons(String json1, String json2) {
Gson _gson = new Gson();
CalcObj obj1 = _gson.fromJson(json1, CalcObj.class);
CalcObj obj2 = _gson.fromJson(json2, CalcObj.class);
CalcObj objSum = new CalcObj();
objSum.json_obj = obj1.json_obj + obj2.json_obj;
return _gson.toJson(objSum );
}

JSONObject parse dictionary objects

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.

JSONObject get value of first node regardless of name

I am wondering if there is a way to get the value of the first child of a JSONObject without knowing its name:
I have some JSON coming in with a node called, this_guy
{"this_guy": {"some_name_i_wont_know":"the value i care about"}}
Using JSONObject, how can I get "the value i care about," cleanly if I don't know the name of the child. All I know is "this_guy", anyone?
Use JSONObject.keys() which returns an iterator of the String names in this object. then use these keys to retrieve values.
To get only first value:
Iterator<String> keys = jsonObject.keys();
// get some_name_i_wont_know in str_Name
String str_Name=keys.next();
// get the value i care about
String value = json.optString(str_Name);
Object obj = parser.parse(new FileReader("path2JsonFIle"));
JSONObject jsonObject = (JSONObject) obj;
try this iterator
JSONObject jsonObj = (JSONObject)jsonObject.get("this_guy");
for (Object key : jsonObj.keySet()) {
//based on you key types
String keyStr = (String)key;
Object keyvalue = jsonObj.get(keyStr);
/*check here for the appropriate value and do whatever you want*/
//Print key and value
System.out.println("key: "+ keyStr + " value: " + keyvalue);
}
once you get the appropriate value, just break out of the loop. for example you said that all you need is the first value in the inner map. so try womething like
int count = 0;
String valuINeed="";
for (Object key : jsonObj.keySet()) {
//based on you key types
String keyStr = (String)key;
Object keyvalue = jsonObj.get(keyStr);
valueINeed = (String)keyvalue;
count++;
/*check here for the appropriate value and do whatever you want*/
//Print key and value
System.out.println("key: "+ keyStr + " value: " + keyvalue);
if(count==1)
break;
}
System.out.println(valueINeed);
if you care only about the value and not about the key, you can use directly this:
Object myValue = fromJson.toMap().values().iterator().next();

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

Categories