Is there a way to convert a Java object to a string like below?
Note that all the filed names should be escaped, and "\n" is used as to separate records.
{
"content":"{\"field1\":123, \"field2\":1, \"field3\":0, \"field4\":{\"sub1\":\"abc\", \"sub2\":\"xyz\"}}\n
{\"field1\":234, \"field2\":9, \"field3\":1, \"field4\":{\"sub1\":\"xyz\", \"sub2\":\"abc\"}}"
}
Thanks,
You can use GSON for that task.
Gson is a Java library that can be used to convert Java Objects into their JSON representation. It can also be used to convert a JSON string to an equivalent Java object. Gson can work with arbitrary Java objects including pre-existing objects that you do not have source-code of.
If you need to have a better readable representation, you may use the pretty-print feature.
Gson gson = new GsonBuilder().setPrettyPrinting().create();
To realize something like your example, you could in a first step serialize your content class, put the resulting string as a property in another class and serialize that one again.
That way GSON takes care of the escaping of ".
If you collect your strings in an array and use the pretty print option shown above, you get something similar to your line-break requirement, but not quite the exact same.
The result of the process described above may look like the following:
{
"content": [
"{\"field1\":123, \"field2\":1, \"field3\":0, \"field4\":{\"sub1\":\"abc\", \"sub2\":\"xyz\"}}",
"{\"field1\":234, \"field2\":9, \"field3\":1, \"field4\":{\"sub1\":\"xyz\", \"sub2\":\"abc\"}}"
]
}
Another alternative is to use the Json-lib library http://json-lib.sourceforge.net
String jsonStrData = " ....... ";
JSONObject jsonObj = JSONObject.fromObject(jsonStrData);
System.out.println(jsonObj);
Like GSON, json-lib handles escaping for you, more info on how to use it here http://json-lib.sourceforge.net/usage.html
Related
I know that most Java json libraries can pretty print by
parsing into a generic model and then
serialising the model.
There are endless existing questions on StackOverflow which tell you to pretty print json this way using Jackson or GSON, e.g Pretty-Print JSON in Java
However, I have found with using Jackson ObjectMapper to do this, if I have decimal value eg "10000.00" it will then parse them into either a BigDecimal or Double and then end up writing it as "10000.0" (double) or "1E+4" (BigDecimal).
What I want is a way of formatting JSON which only affects whitespace, and does not disturb the content of any values - if the input was "10000.00" the output must be "10000.00"
Does anyone know of a Java JSON library that can handle that?
Underscore-java library has static method U.formatJson(json). It will leave the double value as is. 12.0 will be formatted as 12.0. I am the maintainer of the project.
There is a difference between JSONs {"value":5.0} and {"value":"5.0"} in the second case the "5.0" value will be treated as String and will not be modified. In the first case, it will be detected as Numerical and may be modified. So, either make a requirement for your JSON to have numerical values quoted, or do it yourself in your code before parsing the JSON string. Also if you yourself produce the JSON from some object then if you have
private Double myValue;
Have the getter
#JsonIgnore
Double getMyValue() {
return myValue;
}
and add another getter
#JsonProperty(name="myValue")
String getMyValueStr() {
return myValue.toString();
}
All annotations are for Jason-Jackson.
I'm looking for a Java library that can do variable substitution when marshaling Json to an Object on-the-fly.
For example, the Json template would have variable substitution sites/placeholders like:
{
"User": {
"Name": "${name}",
"Age": ${age}
}
}
that would result in the Java Object representing the following once marshaled:
{
"User": {
"Name": "Elvis",
"Age": 80
}
}
What I want is something along the lines of this:
ObjectMapper mapper = new ObjectMapper();
User user = mapper.readValue(new File("c:\\user.json.template"), User.class, "Elvis", 80);
This is really out of scope for JSON libraries, since JSON format itself has no support or notion of variable substitution. Your best bet may be to use a JSON library (like Jackson) to get a tree representation (for Jackson that would be JsonNode), then traverse it, and use another library for handling textual substitution. There are many that can do that, from stringtemplate to others (perhaps MessageFormat that other answer refers to).
It may also be possible to revert the other, if your substitutions will never funny "funny characters" (quotes, linefeeds); if so, you could use string templating lib first, JSON parser next feeding processed text.
But it is bit riskier, as usually there is eventually one case where you do end up trying to add a quote, say, and then parsing fails.
You can use a template engine such as Apache Velocity to preprocess the input stream, and then parse the result with a JSON parser. To make the process "on-the-fly", you can run Velocity in a separate thread, and let it write it's output to a PipedOutputStream.
May be the MessageFormat object from apache commons could help ?
Here is an example : http://examples.javacodegeeks.com/core-java/text/messageformat/java-messageformat-example/
Suppose I have an extremely large data set, where each data item is serialized as a JSON object. When I place these into a file, I have two choices.
(1) I can write them out as one JSON object per line, delimited by carriage returns / newlines:
{ jsonobject }
{ jsonobject }
...
(2) However, the official spec says the above formatting isn't legal. I have to use a JSON array:
[
{ jsonobject },
{ jsonobject }
]
I think the first approach is easier to parse in code because you can read in one text line at a time (I'm using Java and will use BufferedReader.readLine()), and then parse that line into a JSON object.
The second approach may run out of memory depending on what parser you're using, right? The parser may need to read the whole file into memory to construct the array.
What is the best practice for this problem?
I am trying to convert string like this:
{"Shops":[
{"city":"Riga","shops":[{"a":"some info here","b":"...","c":"..."},{"a":"some info here","b":"...","c":"..."}]},{"city":"Liepaja","shops":[{"a":"info here","b":"info....","c":"..."}]
]}
to 2d array, like
shops[0][0]=>{"a":"some info here","b":"...","c":"..."}
shops[1][0]=>{"a":"info here","b":"info....","c":"..."}
Is it possible? Is there some easy way to do that?
I've searched, tried, but I still don't know how to do that.
I'm new in java.
That is a JSON string. There are a number of libraries that will do this for you.
JSON in Java
GSON
That looks like JSON data, and you should treat it as such.
Try a JSON parsing library for Java. I like GSON for its simplicity. Take a look at the Gson.fromJson() set of methods.
The type of data you have posted is JSON encoded. you could use a json encoder and decoder to do this job easily.
I am using JSON-lib library for java http://json-lib.sourceforge.net
I just want to add simple string which can look like JSON (but i do not want library to automatically figure out that it might be json and just to treat it as string). Looking into source of library I can't find the way to do it without ugly hacks.
example:
JSONObject object = new JSONObject();
String chatMessageFromUser = "{\"dont\":\"treat it as json\"}";
object.put("myString", chatMessageFromUser);
object.toString() will give us {"myString":{"dont":"treat it as json"}}
and i want just to have {"myString":"{\"dont\":\"treat it as json\"}"}
How to achieve it without modifying source code ? I am using this piece of code as transport for chat messages from users - so it works OK for normal chat messages, but when user will enter JSON format as message it will break it because of default behavior of JSON-lib described here.
If I understand question correctly, I think json-lib is unique in its assumption of a String being passed needing to be parsed. Other libs typically treat it as String to include (with escaping of double-quotes and backslashes as necessary), i.e. work as you would expect.
So you may want to consider other libraries: I would recommend Jackson, Gson also works.
json-simple offers a JSONObject.escape() method.