How to extract JSON String data? - java

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'

Related

Extract data from json string with or without JSONObject

I've got the following json code stored in a java String:
String str = {"posts":[{"key":"key1","value":"x"},{"key":"key2","value":"0"},{"key":"key3","value":"y"}]}
Is there a way to extract the values from the string using JSONObject or should I use the old school method:
String[] parts = str.split("\"");
In my case the values are stored in the array at the positions: parts[9], parts[17] and parts[25].
It works well so far, but I wonder if I could use JSONObject for that task?
Using JSONObject (from the org.json package, JSON-java), you can easily extract values.
final JSONObject jsonObject = new JSONObject(str);
final JSONArray posts = jsonObject.getJSONArray("posts");
final Collection<String> values = new ArrayList<>(posts.length());
for (int i = 0; i < posts.length(); i++) {
final JSONObject post = posts.getJSONObject(i);
values.add(post.getString("value"));
}
// values = [x, 0, y]
I'd absolutely avoid any kind of manual String manipulation.
Use Gson library provided by google if you are using Java
https://github.com/google/gson
Here you can convert your java to Json and Json back to java objects seamlessly.

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.

String to Array Java to Json object [duplicate]

This question already has answers here:
How to parse JSON in Java
(36 answers)
Closed 5 years ago.
I have a Java String that contains a json object and I do not know how to get this json object from it?
My string is like this:
String myString = "[1,\"{\\\"Status\\\":0,\\\"InstanceNumber\\\":9}\"]";
How can i get the json object from this String?
I would recommend simple plain org.json library. Pass the string in JSONArray and then get the JSONObject. For example something like below :
String myString = "[1,\"{\\\"Status\\\":0,\\\"InstanceNumber\\\":9}\"]";
JSONArray js = new JSONArray(myString);
System.out.println(js);
JSONObject obj = new JSONObject(js.getString(1));
System.out.println(obj);
Output :
[1,"{\"Status\":0,\"InstanceNumber\":9}"]
{"Status":0,"InstanceNumber":9}
Downloadable jar: http://mvnrepository.com/artifact/org.json/json
For sure that you need to use a library lie Jackson or Gson.
I work mostly with gson when I don't have complicated stuff.
So here the output of what you are asking for. I suppose that you don't have the type that you want to convert to (for that I am taking Object).
Here is the code:
import com.google.gson.Gson;
public class Json {
public static void main(String[] args) {
Gson g = new Gson();
String myString = "[1,\"{\\\"Status\\\":0,\\\"InstanceNumber\\\":9}\"]";
Object p = g.fromJson(myString, Object.class);
System.out.println(p.toString());
}
}
And here is the output :
run:
[1.0, {"Status":0,"InstanceNumber":9}]
BUILD SUCCESSFUL (total time: 0 seconds)
You may wanting to manipulate the output object as you wish (I just printed it out).
NOTE: Don't forget to add gson jar to you classpath.
You can use any Json mapping framework to deserialise the String into Java object. Below example shows how to do it with Jackson:
String myString = "[1,\"{\\\"Status\\\":0,\\\"InstanceNumber\\\":9}\"]";
ObjectMapper mapper = new ObjectMapper();
List<Object> value = mapper.readValue(myString, new TypeReference<List<Object>>() {});
Map<String, Object> map = mapper.readValue(value.get(1).toString(), new TypeReference<Map<String, Object>>() {});
System.out.println(map);
Here's the documentation.

How to get a string[] from the following JSON string?

I have the following string
["xyz#live.com","abc#live.com"]
I am using String.split(",") to get String[]. But array contents consist of '[' and '"'.
I need to get the actual strings with out quotes. Is there a library or method with which I can do it?
At present I am doing like this.
recipients = recipients.replace("\"", "");
recipients = recipients.replace("[", "");
recipients = recipients.replace("]", "");
String[] totalRecipients = recipients.split(",");
De-serialize the json string to java object using boon or jackson 3rd party library.
Boon Example -
ObjectMapper mapper = JsonFactory.create();
String[] recipientArray = mapper.readValue(recipients , String[].class, String.class);
Find Java Boon vs jackson json - Benchmarks - here
Source : Link
I suggest you to use json library to solve it.
http://jackson.codehaus.org/
String s = "[\"xyz#live.com\",\"abc#live.com\"]";
ObjectMapper mapper = new ObjectMapper();
JsonNode node = mapper.readValue(s);
for(JsonNode n : node){
.......
}
you can use of google's gson and to decode your json to String[] you can simply use this line of code
Gson gson = new Gson();
String[] myArray = gson.fromJson(yourjson,String[].class);

Insert node in a JSON String

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();

Categories