简体   繁体   中英

Is JSON parsing or String parsing more expensive in Java?

I'm trying to dynamically parse a lot of data in Java. In other words I have tons of different types of data so I am putting them in a String or a JSON String (via GSON) instead of doing:

switch(data){
case instanceof Class1:
     Class1 data = gson.fromJson(jsonString);
     //Do Stuff for class 1 layout
case instanceof Class2:
     Class2 data = gson.fromJson(jsonString);
etc.

So instead of doing this for 80 or so classes (which more may be added/removed/changed at any given time) I am planning to put the data in either a String or Json String and parse out the values (depth first).

I am on a low end PC (single core Atom processor) and am trying to reduce the amount of taxing I put on the CPU, so determining which would be faster... regex string manipulation with splits or using a recursive JSON parser.

Let us discuss both the cases you have mentioned here:

CASE 1: Creating instances for each and every json input using gson (mapped to a Class)

and

CASE 2: Create a Document (or similar type object) itself and try accessing data from there.

For Case 2, you don't need to write a parser yourself: there are parsers already available. I'll just write down a jackson example here (There must be similar stuff available with gson as well):

String myJson = "{ \"type\" : \"foo\", \"class\" : 3 }";
ObjectMapper objectMapper = new ObjectMapper();
JsonNode node = objectMapper.readValue(myJson, JsonNode.class);
JsonNode type = node.get("type");
System.out.println(type.asText());

As per my experience, the performance difference hasn't been much in both these cases as the libraries handle the parsing quite efficiently but if you have a lot of different types of JSON, then it doesn't make any sense to create POJOs out of each and every JSON (So much mapping !!).

I have personally not worked with gson because of performance reasons like this but you can create what's called an ObjectMapper using jackson and use it quite efficiently. I assume there should be similar thing in gson as well.

The only downside would be that every field will now be accessible through a string input which might make your code a bit unreadable.

EDIT:

If you really wish to iterate through all the fields of the json, you'll have to do DFS ultimately, but parsing can still be avoided by using the fields method of the JsonNode.

root.fields() will return with an iterator with the entries in it which can be then gracefully used as described in answer here .

Remember, similar stuff with different names will be available in gson too. :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM