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.
[{"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();
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'
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(), ...