Insert node in a JSON String - java

Using Google Gson library how can I inject a element in the root node of a JSON string?
With JSON.Simple it very easy:
String json = ...
JSONObject jsonObj = (JSONObject) JSONValue.parse(json);
jsonObj.put("hey", "yow!");
json = jsonObj.toJSONString(); // Now we have injected a node element
I've been figuring out how can do this with Gson. You might ask why I need Gson when I can do this with JSON.Simple library; the answer is that, there's a handy object serialization/deserialization function that the library have.

The code is strikingly similar:
String json = ...;
JsonObject jsonObj = (JsonObject) new JsonParser().parse(json);
jsonObj.addProperty("hey", "yow!");
json = jsonObj.toString();

Related

GSON - remove JSON data from JSON object

I'm looking to remove part of a JSON object, at the moment I only seem to be able to return the whole object.
JSON format:
{"blobJson":"{\"sensorID\":\"111122\",\"width\":32,\"height\":31,\"frameData\":[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]}","deviceMfg":2,"eventCode":101,"sensorClass":1,"sensorUUID":"111122","timeStamp":1.53907307310099994E18,"uID":"111122_1_2"}
I'm looking to remove the [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0] part of the JSON.
At the moment I'm using the following code:
JsonParser jp = new JsonParser(); //from gson
JsonElement root = jp.parse(new InputStreamReader((InputStream) request.getContent()));
JsonObject rootobj = root.getAsJsonObject();
System.out.println(rootobj);
This is outputting the following JSON:
{"blobJson":"","deviceMfg":-1,"eventCode":-1,"sensorClass":-1,"sensorUUID":"","timeStamp":0.0,"uID":"_-1_-1"}
If you want to remove the framedata key and value from the string. You can use the org.json.JSONObject as shown below:
JSONObject jo1 = new JSONObject("{\"blobJson\":{\"sensorID\":\"111122\",\"width\":32,\"height\":31,\"frameData\":[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]},\"deviceMfg\":2,\"eventCode\":101,\"sensorClass\":1,\"sensorUUID\":\"111122\",\"timeStamp\":1.53907307310099994E18,\"uID\":\"111122_1_2\"}");
jo1.getJSONObject("blobJson").remove("frameData");
If you want to retain the key framedata but want only the value to be replace with [] then do the following:
JSONObject jo1 = new JSONObject("{\"blobJson\":{\"sensorID\":\"111122\",\"width\":32,\"height\":31,\"frameData\":[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]},\"deviceMfg\":2,\"eventCode\":101,\"sensorClass\":1,\"sensorUUID\":\"111122\",\"timeStamp\":1.53907307310099994E18,\"uID\":\"111122_1_2\"}");
jo1.getJSONObject("blobJson").put("frameData", "[]");
You can use ObjectMapper from com.fasterxml.jackson.databind but then you require the corresponding class also with all the member variables corresponding to the json keys. In the above approach you can directly manipulate the Json String.
String stringifyRequest="{"blobJson":"{\"sensorID\":\"111122\",\"width\":32,\"height\":31,\"frameData\":[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]}","deviceMfg":2,"eventCode":101,"sensorClass":1,"sensorUUID":"111122","timeStamp":1.53907307310099994E18,"uID":"111122_1_2"}";
final ObjectMapper mapper = new ObjectMapper();
"Yourpojoclass" investmentResponse = mapper.readValue(stringifyRequest, "Yourpojoclass".class);
here "Yourpojoclass" would be your class which consists string field parameter:
Now set your frameData value null and make your pojo class #JsonInclude(value=Include.NON_NULL)
and then convert it again in json.

json parsing in java language

[{"name":"RAJGOWTHAMAN R","branch":"B.Tech - Information Technology","details":[{"semester":"6","subcode":"10 IT 611","subname":"Object Oriented Analysis and Design","grade":"C","result":"Pass"},{"semester":"6","subcode":"10 IT 612","subname":"Visual Programming","grade":"C","result":"Pass"},{"semester":"6","subcode":"10 IT 613","subname":"Web Technology","grade":"E","result":"Pass"},{"semester":"6","subcode":"10 IT 614","subname":"Cryptography and Network Security","grade":"E","result":"Pass"},{"semester":"6","subcode":"10 IT 615","subname":"System Software","grade":"D","result":"Pass"},{"semester":"6","subcode":"10 IT 6P1","subname":"Visual Programming Laboratory","grade":"A","result":"Pass"},{"semester":"6","subcode":"10 IT 6P2","subname":"CASE Tools Laboratory","grade":"C","result":"Pass"},{"semester":"6","subcode":"10 IT 6P3","subname":"Web Technology Laboratory","grade":"S","result":"Pass"},{"semester":"6","subcode":"10 IT E13","subname":"Software Quality Management","grade":"RA","result":"Fail"}]}]
how can I parse the above json
There are a number of JSON libraries available in Java:
gson
json-simple
Here's code snippet to parse the JSON string using json-simple:
import org.json.simple.JSONObject;
import org.json.simple.JSONArray;
import org.json.simple.JSONValue;
...
String jsonLine = "[{ ... }]";
// first have to parse JSON into object
Object obj = JSONValue.parse(jsonLine);
JSONArray array = (JSONArray)obj;
JSONObject value = (JSONObject)array.get(0);
// JSONObject extends HashMap so can access properties as any Map
System.out.println("keys=" + value.keySet());
JSONArray details = (JSONArray) value.get("details");
// do something with details object
From your example, this would output:
keys=[name, details, branch]
json-simple has many examples to decode JSON:
https://github.com/fangyidong/json-simple/wiki
Using gson the code is nearly identical:
JsonElement jelement = new JsonParser().parse(jsonLine);
JsonElement value = jelement.getAsJsonArray().get(0);
JsonArray details = value.getAsJsonObject().get("details").getAsJsonArray();

JSON traversing in java

i want traverse and get particular value from the json i am giving below .
json={"resultMessage":["{\"retain24ErrorMessage\":\"No result data found!\"}","TemplateId or instanceId is empty!"],"isSuccessful":true}
The value i want to get is retain24ErrorMessage value. I have tried the following.
Object JSONArrayCheck = json.get("resultMessage");
String errMsg1 = (String)json.getJSONArray("resultMessage").get(0);
Gson gson = new Gson();
// JsonElement jsonObject = gson.toJsonTree(json.getJSONArray("resultMessage").get(0));
JsonElement jelement = new JsonParser().parse(gson.toJson(errMsg1));
JsonObject jobject = jelement.getAsJsonObject();
But is not working and following error comes
12-11 17:17:16.300: W/System.err(1780): java.lang.IllegalStateException: Not a JSON Object: "{\"retain24ErrorMessage\":\"No result data found!\"}"
. Can you give me demo for retrieving the same retain24ErrorMessage ?
gson.toJson(errMsg1) expects an Object but the passed errMsg1 is a string.
Don't you need to do something like this instead?
JsonElement jelement = new JsonParser().parse(errMsg1);

How to extract JSON String data?

I have JSON string which is in a standalone Java project:
{"MsgType":"AB","TID":"1","ItemID":"34532136","TransactTime":1389260033223}
I want to extract MsgType from this which is AB
Which is the best way to do it?
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);
I have an example with json-simple:
JSONParser parser = new JSONParser();
JSONObject jsonObject = (JSONObject) parser.parse(yourString);
String msgType = (String) jsonObject.get("MsgType");
Check this link for a complete example.
JsonPath
For parsing simple JSON use JsonPath
JsonPath is to JSON what XPATH is to XML, a simple way to extract parts of a given document.
Example code
String json = "{\"MsgType\":\"AB\",\"TID\":\"1\",\"ItemID\":\"34532136\",\"TransactTime\":1389260033223}";
String author = JsonPath.read(json, "$.MsgType");
System.out.println(author);
Result
AB
Dependency
'com.jayway.jsonpath:json-path:0.9.1'

Java JSON parse array

I am using the following library to parse an object:
{"name": "web", "services": []}
And the following code
import com.json.parsers.JSONParser;
JSONParser parser = new JSONParser();
Object obj = parser.parseJson(stringJson);
when the array services is empty, it displays the following error
#Key-Heirarchy::root/services[0]/ #Key:: Value is expected but found empty...#Position::29
if the array services has an element everything works fine
{"name": "web", "services": ["one"]}
How can I fix this?
Thanks
Try using org.json.simple.parser.JSONParser
Something like this:
JSONParser parser = new JSONParser();
JSONObject jsonObject = (JSONObject) parser.parse(stringJson);
Now to access the fields, you can do this:
JSONObject name = jsonObject.get("name"); //gives you 'web'
And services is a JSONArray, so fetch it in JSONArray. Like this:
JSONArray services = jsonObject.get("services");
Now, you can iterate through this services JSONArray as well.
Iterator<JSONObject> iterator = services.iterator();
// iterate through json array
while (iterator.hasNext()) {
// do something. Fetch fields in services array.
}
Hope this would solve your problem.
Why do you need parser?
try this:-
String stringJson = "{\"name\": \"web\", \"services\": []}";
JSONObject obj = JSONObject.fromObject(stringJson);
System.out.println(obj);
System.out.println(obj.get("name"));
System.out.println(obj.get("services"));
JSONArray arr = obj.getJSONArray("services");
System.out.println(arr.size());
I solve the problen with https://github.com/ralfstx/minimal-json
Reading JSON
Read a JSON object or array from a Reader or a String:
JsonObject jsonObject = JsonObject.readFrom( jsonString );
JsonArray jsonArray = JsonArray.readFrom( jsonReader );
Access the contents of a JSON object:
String name = jsonObject.get( "name" ).asString();
int age = jsonObject.get( "age" ).asInt(); // asLong(), asFloat(), asDouble(), ...
Access the contents of a JSON array:
String name = jsonArray.get( 0 ).asString();
int age = jsonArray.get( 1 ).asInt(); // asLong(), asFloat(), asDouble(), ...

Categories