The format of my json object is:
String jsonObjRecv = {
"response":{
"respobj":{
"id":<int>,
"number":<string>,
"validated":<boolean>
}
},
"status":"ok",
"errors":null
}
It works when code is:
JSONObject jsonObjCont = new JSONObject(jsonObjRecv);
String getString= jsonObjCont.toString(2);
In this case getString != null and I can receive data, but when I try to get nested data of JSON object as like:
JSONObject jsonObjCont = new JSONObject(jsonObjRecv);
JSONObject regNumber = jsonObjCont.getJSONObject("respobj");
String number= regNumber.getString("number");
it dont work.
I tried to use GSON library, but it works when:
public String parse(String jsonObjRecv) {
JsonElement jelement = new JsonParser().parse(jsonObjRecv);
String result = jelement.toString();
return result;
and don't work :
public String parse(String jsonObjRecv) {
JsonElement jelement = new JsonParser().parse(jsonObjRecv);
JsonObject jobject = jelement.getAsJsonObject();
jobject = jobject.getAsJsonObject("respobj");
String result = jobject.get("number").toString();
return result;
Where is my mistake?
The problem is you're not accessing your JSON object correctly - it's an object that contains a response object which contains a respobj object.
Gson example follows. Note the comment in the code - you need to get the response object then get the respobj from it.
public static void main( String[] args )
{
String jsonObjRecv = "{\"response\":{\"respobj\":{\"id\":1,\"number\":\"22\",\"validated\":true}},\"status\":\"ok\",\"errors\":null}";
JsonElement jelement = new JsonParser().parse(jsonObjRecv);
JsonObject jobject = jelement.getAsJsonObject();
// Here is where you're making an error. You need to get the outer
// 'response' object first, then get 'respobj' from that.
jobject = jobject.getAsJsonObject("response").getAsJsonObject("respobj");
String result = jobject.get("number").getAsString();
System.out.println(result);
}
Output:
22
Edit to add: Note I used getAsString() vs. toString() - if you use the latter you get the raw JSON which will incluse the quotes around the value (e.g. the output would be "22")
Related
I have Json stored in javax.json.JsonObject, the object look like this:
{
"status":"ok",
"meta":{
"count":2
},
"data":{
"1":{
"id":40,
},
"17":{
"id":48,
}
}
}
How do I access the id key in the sub-object "1" ?
I tried:
obj.getJsonArray("data").getJsonArray("1").getJsonNumber("id").intValue();
However it does not work because the firt call of getJsonArray() method returns a JsonValue object not a JsonObject so the next call of getJsonArray fails. Any ideas ?
You can use an iterator approach to iterate thru the JSONObject:
JSONObject json = new JSONObject(input);
JSONObject jsonData = json.getJSONObject("data");
Iterator<?> jsonDataKeys = jsonData.keys();
while (jsonDataKeys.hasNext()) {
String key = (String)jsonDataKeys.next();
if (jsonData.get(key) instanceof JSONObject) {
System.out.println(((JSONObject) jsonData.get(key)).getInt("id"));
}
}
int id = obj.getJsonObject("data")
.getJsonObject("1")
.getInt("id");
JSONObject jObject = null;
jObject = new JSONObject(String you want to parse);
JSONObject j1Object = jObject.getJSONObject("data");
JSONObject j2Object = j1Object.getJSONObject("1");
String s1=j2Object.getString("id");
System.out.println(s1);
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 );
}
I have been working on a project that requires JSON for getting data from a large json file, but I ran into a problem when trying to get a json string using a method.
the method for getting the ID works I have tested this multiple times. When I enter int he ID as a string it also works prefectly but when I use the method to get the jsonString it stops working and gives a nullpoiterexeption
public static int getLvlMin(ItemStack is) throws ParseException {
String id = getID(is);
system.out.println(id);
JSONParser parser = new JSONParser();
Object obj = parser.parse(Main.weapons);
JSONObject jsonObj = (JSONObject) obj;
system.out.printlnjsonObj.toJSONString());
JSONObject weapon = (JSONObject) jsonObj.get(String.valueOf(getID(is)));
system.out.println(weapon.toJSONString());
return 1;
}
This is the json string I am trying to get info {"W1121000-00002":{"clnt":1023,"srvr":870}} and I am trying to get the clnt value out of that string.
We have a requirement to update the JSON data in middle and need to return the updated JSON data using java. Also it should support any type of JSON data.
ex:
Assume {object:{"color":"red","shape":"Triangle"}} is the JSON data and in this we need to update the shape value to Rectangle and we need to return the updated JSON data as below:
{object:{"color":"red","shape":"Rectangle"}}
For this we need to pass the element path ( which element we need to update) and updateText and JSON Data to the JAVA code.
here is the methodCall:
updateValue("object/shape", "Rectangle", "{object:{"color":"red","shape":"Triangle"}}")
We tried below code using Gson library. But with this code we are able to update the targeted Json element, but the requirement is to return the entire JSON data with the updated value.
So please suggest how do we re-build the JSON data with the updated text.
Below is the code we tried to update the Json Data.
public String updateValue(String keyPath, String updateText, String jsonText) {
String[] keys = keyPath.split("/");
JsonParser jsonParser = new JsonParser();
JsonObject jsonObject = (JsonObject) jsonParser.parse(jsonText);
String result = "";
for(String key : keys)
{
if (jsonObject.get(key) instanceof JsonObject)
{
jsonObject = (JsonObject)jsonObject.get(key);
}
else if(jsonObject.get(key) instanceof JsonArray)
{
JsonArray jsonArray = (JsonArray)jsonObject.get(key);
result = jsonArray.toString();
}
else
{
result = jsonObject.get(key).toString();
}
}
result = result.replace(result, updateText);
return result;
}
The problem lies in the way you do the replacements. When you translate the JsonObject to String, you lose the object, and after replacement, you just have the replaced String. To fix it, you need to operate directly on the object, instead of the String counterpart. Because JsonObject is mutable, holding a reference to the input will reflect the changes. One drawback is you can't replace a value in a JsonArray this way, partly because you don't know which element to replace. To accomplish that, you will need a little more in the input(either the value to replace or the element position).
public String updateValue(String keyPath, String updateText, String jsonText) {
String[] keys = keyPath.split("/");
JsonParser jsonParser = new JsonParser();
JsonObject jsonObject = (JsonObject) jsonParser.parse(jsonText);
JsonObject returnVal = jsonObject; // This holds the ref to target json object
JsonPrimitive jp = new JsonPrimitive(updateText);
String finalKey = keys[keys.length - 1];
for(String key : keys)
{
if (jsonObject.get(key).isJsonObject())
{
jsonObject = (JsonObject)jsonObject.get(key);
}
}
jsonObject.remove(finalKey);
jsonObject.add(finalKey, jp);
return returnVal.toString();
}
You can use JsonPath lib for that and try using the following code.
private static final Configuration configuration = Configuration.builder()
.jsonProvider(new JacksonJsonNodeJsonProvider())
.mappingProvider(new JacksonMappingProvider())
.build();
JsonNode updatedJson = JsonPath.using(configuration).parse(originaljson)
.set("use the path to go for value", "new value").json();
json = updatedJson.toString();
I have this piece of code that was working and all of a sudden is now throwing a Cast Exception. Have anyone experienced something similar? Thanks.
#Override
public List<RecordJSONclass> handleResponse(HttpResponse response)
throws IOException {
List<RecordJSONclass> result = new ArrayList<RecordJSONclass>();
String JSONResponse = new BasicResponseHandler().handleResponse(response);
try {
JSONObject object = (JSONObject) new JSONTokener(JSONResponse).nextValue();
JSONObject earthquakes = object.getJSONObject("data");
JSONArray temp = earthquakes.getJSONArray("temperature");
JSONArray prob = earthquakes.getJSONArray("pop");
is throwing a
java.lang.ClassCastException: java.lang.String cannot be cast to
org.json.JSONObject
at myxmlparser.ResponseHandlerJSON.handleResponse(ResponseHandlerJSON.java:22)
The exception happens at line
JSONObject object = (JSONObject) new
JSONTokener(JSONResponse).nextValue();
however a String is passed as example in the Class overview in http://developer.android.com/reference/org/json/JSONTokener.html
Well, it is the return value. The nextValue method does not return a JSONObject. It returns a String in this case.
From the Javadoc:
Object nextValue() - Returns the next value from the input.
So, you can't assume that it is a JSONObject.
So, to get hold of the correct value simply use:
String val = (String) new JSONTokener(JSONResponse).nextValue();