What's the fastest way to build a JSON string in java? - java

I'm working with JSON on the server for the first time. I'm trying to create an object that looks like this:
{
columnData : {
column1 : {"foo": "bar", "value" : 1 },
},
rowData : {
row1 : {"type" : "integer", "value" : 1},
}
}
Essentially, it's a two-level JSON object in which I've got all objects on the top level. Everything on the second level will be a string, and integer, or a float. I've found several ways I could go about creating this JSON string:
Build the string directly
I can go through one line at a time and build up a giant string. This seems unwieldy.
Use gson
I can build a map (or class?) that has the structure of the JSON I want, and then use gson to convert to a JSON string.
Use JsonObject
This would work like this question. I just found that example, and I like how simple working with JSON looks in it, but I'm not sure if it's a better way to go than the other options.
I'm pretty new with Java, so I'm not really sure what the performance tradeoffs of these methods are. I do know that I'll potentially be calling this method lots of times very quickly to load data into a client as the user scrolls a table in a webapp, so I'd like everything to be as fast as possible. What's the quickest way to go about building the JSON string that I'll then be sending back to the client?

Depends on what "fastest" means. Fast to develop or fast in terms of performance.
Fastest on dev is to use a library to serialize existing data structures directly to JSON. Use the following library.
http://flexjson.sourceforge.net
Performance wise comparisons it matches Jackson and beats in some cases and destroys gson. But that means you would be serializing your data structures directly rather than mapping them by hand with JSONObject or something like that.
You may be able to get a faster transaction / sec by using JSONObject by hand and mapping your data structures to it. You might get better performance, but then you might not because you have to new up JSONObject and convert the data to it. Then allow JSONObject to render. Can you write hand written code better than a serializing library? Maybe, maybe not.

Related

Parsing JSON string and preserving key-data order when using json-simple without manually constructing HashMap

I know that this topic has been talked about, and the use of a LinkedHashMap is a 'hacky' way to maneuver this, but if I'm given thousands of JSON strings as input, and eventually want to output them back in their original form, is there anyway to preserve the order without manually constructing LinkedHashMaps.
For example a string like this
{"key":1,"surname":"Reed","given":"Ryan","address":{"state":"CA","postal":"90210"},"gender":"M"}
Right now if I parse the object like so:
JSONObject jsonObject = (JSONObject) parser.parse(str);
System.out.println(jsonObject);
My output will look like this:
{"surname":"Reed","gender":M,"address":{"postalCode":"90210","state":"CA"},"key":1,"given":"Ryan"}
Is there anyway I can get the output to match exactly like the given input?
In Json property structure, order does not matter. but if you have specific order in your mind you can use Jackson to order them in you desirable way, both in your server and client apps.
https://www.baeldung.com/jackson
http://www.davismol.net/2016/10/24/jackson-json-using-jsonpropertyorder-annotation-to-define-properties-serialization-order/
I think it is impossible by default.
You can refer to this RFC https://www.ietf.org/rfc/rfc4627.txt
An array is an ordered sequence of zero or more values.
If you want to hack it you can override the data structure and use the data structure which preserves the order.

Spring/Jackson Mapping Inner JSON Objects

I have a RESTful web service that provides JSON that I am consuming. I am using Spring 3.2 and Spring's MappingJacksonHttpMessageConverter. My JSON looks like this:
{
"Daives": {
"Daive": {},
"Daive": {},
"Daive": {},
"Daive": {}
}
}
Now everything I have read seems to indicate that this JSON should be refactored to an array of JSON Daives. However, this is valid JSON so I want to make sure that I am thinking correctly before going back to the service provider to ask for changes. In the format above, I would have to know ahead of time how many Daives there are going to be such that my DTO accounted for them. The handy dandy Jackson mapper isn't going work with this kind of JSON setup. If the JSON was altered to provide and Array of JSON Daives, I could use a List to dynamically map them using Spring/Jackson.
Am I correct? Thanks :)
According to this thread, the JSON spec itself does not forbid multiple fields with the same name (in your case, multiple fields named "Daive" in the object "Daives").
However, most parsers will either return an error or ignore any value but the last one. As you said, putting these values into an array seems much more sensible; and indeed, you'll be able to map this array to a List with Jackson.

read large json file

I have a json file with complex structure.
{"Objects":{"items":{"item":[
{
"field1": "value1",
"field2": "value2",
"field3":[
{
"label1":"1",
"label2":"2"
},
{
"label1":"3",
"label2":"4"
}]
}
,
{
//same structure as above object
}
]}}}
The file size is a little more than 1GB. I need to read an object and see what the value of a particular label is and if it matches the list I have, I need to write that object in another file else not.
I know normal JSON parser like JSONSimple won't work as it hold the data into the memory. I am trying to use Jackson, but finding hard to go over all objects as it takes one token at a time. What is an efficient way to use streaming and tree structure of Jackson for this JSON format.
Or in what way can I use script to get the data and use it?
Probably you could advance the JsonParser several times calling nextToken() until you get Token ID_START_ARRAY, call nextToken() to move to the start of the first item object and then feed the parser and POJO class representing "item" into ObjectMapper.readValue() (https://github.com/FasterXML/jackson-databind/blob/master/src/main/java/com/fasterxml/jackson/databind/ObjectMapper.java), repeat until no more objects are found. POJO can be hand-written or generated using something like https://github.com/astav/JsonToJava/wiki/JsonToJava
Or skip Jackson entirely - write a little tokenizer yourself that will extract individual "item" json elements and feed them into JSONSimple. This way you'll maybe have a bit of wheel reinvention, but will avoid getting a lot of dependencies.

Converter from Json into groovy CODE?

It's a kind of odd question for an odd situation. I have a large JSON structure which I would like to represent in running groovy code. I need groovy objects that mirror the same structure as the JSON objects.
As to be expected a web search mostly returns results with groovy/json runtime conversion stuff, but nothing about things that output groovy code.
You might think this lazy but really it is a massive JSON structure! A converter would save days!
You can use Groovy's own JsonSlurper to parse JSON objects:
import groovy.json.*
def json = '{"name":"john", "surname":"doe", "languages": ["groovy", "python"]}'
def obj = new JsonSlurper().parseText(json)
assert obj.name == "john"
assert obj.surname == "doe"
assert obj.languages.containsAll("python", "groovy")
Of course the class is untyped: it's only known at runtime. If you want it to be typed, you can write a code which writes the code based on an example (since a json schema may be rare).
EDIT: if you want to generate the model classes code, you can try JSONGen, which "parses JSON to create client side source files to model the JSON data structure". I'm not aware of a solution for Groovy, but since java-groovy integrations is seamless, it shall work fine.
If you want a Groovy representation of your JSON, you can get that via the built-in JsonSlurper. This will give you Java Maps and Lists of data you can work with.
You can populate more specific, custom objects you've written to represent your JSON entities using the (3rd party) Jackson's data binding functionality (see this question as well).
Try using a JSON parser like this one. According to its documentation you just need to do
JSON.parse
to deserialize the data

Parsing complex string of JSON in java

I want to parse a JSON string which is quite complex. It has somewhat following format
{ A:{ list of around 20 objects},B:1}
These objects inside A again contains some other objects or the datatypes supported by JSON. I have checked couple of examples and documentations.
I found this example to be helpful
Converting JSON to Java
but looks like I need to know each and every element of the objects contained. I can write a similar code but before spending so much effort I wanted to check if there is other libraries out there which can do automatic parsing and By just giving the key field I can get those contents.
Jackson should be able to handle the structure with no problem. You do not need to know the exact structure of the JSON. You can just iterate over all of the objects and inter-objects.

Categories

Resources