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