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);
Related
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 a JSON string which is a list of String
String jsonString = "['String1','String2','String3']";
I am trying to convert it into a List
List<String> list = new ObjectMapper().readValue(jsonString, List.class);
But it is giving me java.lang.NullPointerException
Can any one help me in finding out what is wrong with it?
Edit 2 : Keeping the original post and removing things which may confuse others.
String jsonString = "['String1','String2','String3']"; is not JSON format.
Tried with double quotes ?
String jsonString = "[\"String1\",\"String2\",\"String3\"]";
List<?> list = new ObjectMapper().readValue(jsonString, List.class);
Simple quote is not valid
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 getting the data from the Zookeeper node like this
byte[] bytes = client.getData().forPath("/my/example/node1");
String ss = new String(bytes);
Here ss will have data like this which is a simple JSON String consisting of key value pair -
{"description":"Some Text", "machinename":"machineA", "ipaddress":"192.128.0.0"}
Now I want to append one more key value pair at the end to the above JSON String. This is the below key value pair I want to append -
"version":"v3"
So the final JSON String will look like this -
{"description":"Some Text", "machinename":"machineA", "ipaddress":"192.128.0.0", "version":"v3"}
What's the best and efficient way to do this?
Use a JSON Parser/Generator to parse your given JSON to a tree structure and then add your JSON field.
With Gson, that would look something like this
Gson gson = new Gson();
JsonObject jsonObject = gson.fromJson(ss, JsonObject.class); // parse
jsonObject.addProperty("version", "v3"); // modify
System.out.println(jsonObject); // generate
prints
{"description":"Some Text","machinename":"machineA","ipaddress":"192.128.0.0","version":"v3"}
Will Zookeeper always return valid JSON or their custom format? Be aware of that.
When it comes to JSON processing, string manipulation only works in special and simple cases. For the general case, a good JSON parser library should be used.
Jackson is among the top of such libraries in terms of performance, efficiency, versatility and reliability, plus it is published under the commercial-friendly Apache 2.0 license.
Following is a simple implementation of the requested answer in Jackson.
public static void main(String[] args)
{
String ss = "{\"description\":\"Some Text\", \"machinename\":\"machineA\", \"ipaddress\":\"192.128.0.0\"}";
System.out.println("JSON string before: " + ss);
try
{
ObjectMapper mapper = new ObjectMapper();
Map<String, String> map = (Map<String, String>)mapper.readValue(ss, Map.class);
map.put("version", "v3");
ss = mapper.writeValueAsString(map);
}
catch (Exception e)
{
e.printStackTrace();
}
System.out.println("JSON string after: " + ss);
}
Basic string manipulation. Insert your additional string before the final close brace }. Make sure to add a comma.
Json objects don't need to be ordered.
String json = "{\"key1\":\"value1\",\"key2\":\"value2\"}";
String json2 = "\"version\":\"v3\"";
json2 = ',' + json2;
String json3 = json.substring(0,json.length()-1) + json2 + json.charAt(json.length()-1);
That should be the simplest, most efficient way, if that's all you need to do.
For additional reading on String manipulation,
http://docs.oracle.com/javase/tutorial/java/data/manipstrings.html
In the client side, I have constructed a JSOnARRAY like this:
{"filterEntries":[{"dataName":"mainContact","filterValue":"BILLGATES"}]}.
On the server side (java), I can retireve the values using :
jfilter = JSONValue.parse(jsonFilterStr); //jsonFilterStr={"filterEntries":[{"dataName":"mainContact","filterValue":"BILLGATES"}]}.
JSONArray jFilterEntries = (JSONArray) jfilter.get("filterEntries");
for (int i=0;i<jFilterEntries.size();i++){
JSONObject jFilterEntry = (JSONObject) jFilterEntries.get(i);
String dataName = (String) jFilterEntry.get("dataName");
String filterValue = (String) jFilterEntry.get("filterValue");
}
But the existing app is using flex.json.deserializer and I am unable to achieve the same using flex.json.deserializer. How should I proceed?
I wish to do something like this:
JSONDeserializer jsonDeserializer = new JSONDeserializer();
jsonDeserializer.use(null, List.class);
List<Map<String,String>> lMap= (List<Map<String,String>>)jsonDeserializer.deserialize(params);
Remember the top object that wraps the array. You have to handle that as well. You have to tell it to expect a Map inside the List. To do that you have to specify the type contained in the list by using the path expression "values".
Map<String,List<Map<String,String>>> result = new JSONDeserializer<Map<String,List<Map<String,String>>>>()
.use("values",List.class)
.use("values.values", Map.class)
.deserialize( json);
List<Map<String,String>> filterEntries = result.get("filterEntries");
Updated: Add the new keyword, and made the generic types on the right match the left.