serialization symbol \" from Jackson - java

When I serialize String element with \" inside, result is "{\"role\":\"student\", \"userType\":\"techer\"}" How to change result to "{"role":"student", "userType":"techer"}"? Used java, jackson lib.
String value = "{\"role\":\"student\", \"userType\":\"techer\"}";
System.out.println(value); //{"role":"student", "userType":"techer"}
String json2 = new ObjectMapper().writeValueAsString(value);
System.out.println(json2);// "{\"role\":\"student\", \"userType\":\"techer\"}"

Related

JSONSerializer.toJSON ignores key 'class'

How to convert JSON string to JSON by using JSONSerializer if the JSON string contains 'class' key? By using toJSON method all 'class' keys are ignored:
String str = "{'test': 'ok', 'class' : 'fail'}";
JSON json = JSONSerializer.toJSON(str) // result is: {"test":"ok"}
I found it:
JsonConfig cfg = new JsonConfig();
cfg.setIgnoreDefaultExcludes(true);
JSON json = JSONSerializer.toJSON(str, cfg) // {"test":"ok", "class":"fail"}

How to convert string to json string and object in java

This is My String
{Line:1,Direction:incoming,LocalUsername:xxx,AuthUsername:31223,PeerUsername:04232000113,Name:04232000113,Server:23424,Connectime:2189msec,Duration:0msec,DiscBy:Remote,Reason:cancelNormalcallclearing}
i want to convert it to json string
{"Line":"1","Direction":"incoming","LocalUsername":"xxx","AuthUsername":"31223","PeerUsername":"04232000113","Name":"04232000113","Server":"23424","Connectime":"2189msec","Duration":"0msec","DiscBy":"Remote"}
Since it isn't nested, simply add " around : and ,, and after { and before }:
s = s.replaceAll("(?<=[{:,])|(?=[:,}])", "\"");
See demo on regex101.com.
Try using Gson library
Gson g = new Gson();
Player p = g.fromJson(jsonString, Player.class)
You can also convert a Java object to JSON by using toJson() method as shown below
String str = g.toJson(p);
If you don't have a POJO representing the data, it can be done generally using JsonElement.
Demo
String input = "{Line:1,Direction:incoming,LocalUsername:xxx,AuthUsername:31223,PeerUsername:04232000113,Name:04232000113,Server:23424,Connectime:2189msec,Duration:0msec,DiscBy:Remote,Reason:cancelNormalcallclearing}";
Gson g = new Gson();
JsonElement root = g.fromJson(input, JsonElement.class);
String result = g.toJson(root);
System.out.println(result);
Output
{"Line":1,"Direction":"incoming","LocalUsername":"xxx","AuthUsername":31223,"PeerUsername":"04232000113","Name":"04232000113","Server":23424,"Connectime":"2189msec","Duration":"0msec","DiscBy":"Remote","Reason":"cancelNormalcallclearing"}

In Java how to easily get the value of a nested key from a JSON String / Object

I am using Java.
I have a string that I have converted to a JSON Object.
I want to extract the value of one of the Keys.
At the moment I am using this code:
String imageId = myJsonObject.getJSONObject("meta")
.getJSONObject("verification")
.getJSONObject("derivedData")
.getJSONArray("images")
.getJSONObject(0)
.getString("imageID");
This code works but surely there must be an easier way. In javascript I could access the value simply by writing this:
myJsonObject.meta.verification.derivedData.images[0].imageId
You may need to install library such as JsonPath to help you select values from a JSON object
An example to help understand better.
You can use external library Gson
Gson gson=new Gson();
/*You can convert to your DTO as well */
Map<Object,Object> map = gson.from(myJsonObject,Map.class);
Other way is using objectmapper example of fasterxml.
ObjectMapper objectMapper=new ObjectMapper();
/*You can convert to your DTO as well */
objectMapper.readValue(data, Map.class);
Try JsonNode by below step
String imageId= jsonNode.
findPath("meta")
.findPath("verification")
.findPath("derivedData")
.findPath("images")
.get (0).findPath ("imageID").asText ();
You need to use the 'Java API for JSON Binding' JSON-B instead of JSON-P. Using JSON-B you can serialize and deserialize between Java objects and data streams and access values of objects POJO style (similar to what you expect).
API details can be found here
A quick start tutorial can be found here and at many website only google search away..
I have created a small class for this purpose which can basically get value from json using a path only used google.gson
https://github.com/izeryab/JsonParser
Here is how to use this for getting nested value from json:
public class Main {
public static void main(String[] args) {
String json = "{\"data\":[{\"stuff\":[\n" + " { \"onetype\":[\n"
+ " {\"id\":1,\"name\":\"John Doe\"},\n" + " {\"id\":2,\"name\":\"Don Joeh\"}\n"
+ " ]},\n" + " {\"othertype\":[\n" + " {\"id\":2,\"company\":\"ACME\"}\n" + " ]}]\n"
+ "},{\"otherstuff\":[\n" + " {\"thing\":\n" + " [[1,42],[2,2]]\n" + " }]\n" + "}]}";
String name = JsonUtil.getJsonElementFromJsonStringUsingPath("data>0>stuff>0>onetype>0>name", json, ">").getAsString();
int id= JsonUtil.getJsonElementFromJsonStringUsingPath("data>0>stuff>0>onetype>0>id",json,">").getAsInt();
System.out.println("id : "+id);
System.out.println("name : "+name);
}
}
Corresponding JAVA DOCS:
https://izeryab.github.io/JsonParser/JsonUtil.html
You can use GSon, I've used it before (see below)
// Convert to a JSON object to print data
JsonParser jp = new JsonParser(); //from gson
JsonElement root = jp.parse(new InputStreamReader((InputStream) request.getContent())); //Convert the input stream to a json element
JsonObject rootobj = root.getAsJsonObject(); //May be an array, may be an object.
JsonArray jsonDataArray = rootobj.getAsJsonArray("data");
JsonPrimitive totalJson = rootobj.getAsJsonPrimitive("total");
JsonPrimitive nextJson = rootobj.getAsJsonPrimitive("next");

Why ObjectNode adds backslash in in Json String

Here is how I am trying to convert an object to json String
ObjectNode batch = OBJECT_MAPPER.createObjectNode();
String s = OBJECT_MAPPER.writeValueAsString((triggerCommands.getCommands()));
batch.put("commands", s);
System.out.println("raw String= " + s);
System.out.println("ObjectNode String = " + batch);
Which results in output of;
raw String= [{"cmdid":"a06c00d4-5b8b-4313-a8f3-5663dde0fa5b","type":"test"}]
ObjectNode String = {"commands":"[{\"cmdid\":\"a06c00d4-5b8b-4313-a8f3-5663dde0fa5b\",\"type\":\"test\"}]"}
I am curious to know why the String gets backslash when I add it into as value of ObjectNode. All i want is
ObjectNode String = {"commands":[{"cmdid":"a06c00d4-5b8b-4313-a8f3-5663dde0fa5b","type":"test"}]}
There is a similar question asked here but has no solid answer that worked.
Since you're working in the JsonNode domain, you want Jackson to convert your commands to a JsonNode, not a String. Like this:
ObjectNode batch = OBJECT_MAPPER.createObjectNode();
JsonNode commands = OBJECT_MAPPER.valueToTree(triggerCommands.getCommands());
batch.set("commands", commands);
I just read some sourcecodes toString() method of ObjectNode class, calls a TextNode.appendQuoted then a static method CharTypes.appendQuoted(StringBuilder sb, String content), this adds the ( " ) when the object is writed by toString(), here.. when is found a char " then it adds a backlash.
Since your key(s) is a Object array, if you check ObjectNode.put implementation its doesn't allow you add a key as array so.. it need to be parsed to a String
Note you wont get this.
ObjectNode String = {"commands":[{"cmdid":"a06c00d4-5b8b-4313-a8f3-5663dde0fa5b","type":"test"}]}
because the key it's not with between a " (quotes) and as a I told
ObjectNode doesn't allow you a key of type array.
private String writeUnicodeString() {
ObjectMapper mapper = new ObjectMapper();
ObjectNode node = mapper.getNodeFactory().objectNode();
node.put("field1", "Hello World");
return node.toString();
}
This outputs:
{"field1":"Hello World"}

Remove quotes from json array

I have the following problem:
I have an ArrayList in Java.
I convert the ArrayList to string like this:
Gson gson = new Gson();
String feeds += gson.toJson(arrayList);
This is the result:
[{"status":"ERROR","position":"[48.2748206,8.849529799999999]"}]
But i need the following output:
[{"status":"ERROR","position": [48.2748206,8.849529799999999]}]
The Value of position should be without quotes. How can i realize that?
Many thanks in advance
Greets
Replace the double quotes around position's value using String#replaceAll() method. Just create a regex and replace double quotes with empty sting.
Try with Positive Lookbehind and Positive Lookahead.
sample code:
String json = "[{\"status\":\"ERROR\",\"position\":\"[48.2748206,8.849529799999999]\"}]";
String regex = "(?<=\"position\":)\"|\"(?=\\}\\])";
System.out.println(json.replaceAll(regex, ""));
Here is DEMO
Try with grouping and substitutions as well.
sample code:
String json = "[{\"status\":\"ERROR\",\"position\":\"[48.2748206,8.849529799999999]\"}]";
String regex = "(\"position\":)\"([^\"]*)\"";
System.out.println(json.replaceAll(regex, "$1$2"));
Here is DEMO
I don't think you should go like this, may be you should change your work structure, But if you do want to typecast manually, then you can do it this way.
Suppose you have a JSONArray object like this:
JSONArray arr=[{"status":"ERROR","position":"[48.2748206,8.849529799999999]"}];
Then you can take out JSONObject like this:
Iterator iterator = array.iterator();
while(iterator.hasNext()){
Gson gson = new Gson();
ClassToCastInto obj = gson.fromJson((JsonElement)iterator.next();, ClassToCastInto.class);
System.out.println(obj.someProperty);
}
Consider using a Gson JsonWriter:
StringWriter buffer = new StringWriter();
JsonWriter writer = new JsonWriter(buffer);
writer.beginArray().beginObject();
writer.name("status").value("ERROR");
writer.name("position").beginArray();
for (double value : Arrays.asList(48.2748206, 8.849529799999999)) {
writer.value(value);
}
writer.endArray().endObject().endArray().close();
String json = buffer.toString();

Categories

Resources