looking for fastest way string to JSONObject in Android - java

I used to use new JSONObject(string) to convert string to JSONObject. however, it is too slow performance-wise. Anybody have the faster solution?

Take a look at Jackson. They claim to be faster than any other Java JSON parser. It also parses the data in a stream, lowering memory consumption.

I've used Gson with some good success: http://code.google.com/p/google-gson/

Related

JSON performance

I have to turn a List<Map> into a JSON string. The Maps are flat and containing primitive and String data. Right now I'm using GSON. Basically like this:
List<Map> list = new ArrayList();
Map map = new HashMap();
map.put("id",100);
map.put("name","Joe");
map.put("country","US");
// ...
list.add(map);
Gson gson = new GsonBuilder().disableHtmlEscaping().setPrettyPrinting().create();
Stopwatch sw = Stopwatch.createStarted(); // guava's stopwatch
String s = gson.toJson(list);
System.err.println("toJson laps " + sw);
return s;
The list may have 100 entries and each map aprox. 20 fields. GSON really takes long time to create the JSON string. The JSON string will be returned by a HTTP response and right now it took too much time (8000ms). So I try other ones: json-smart, jackson, etc. But no one gives a significant speed boost. I trace the JSON string creation as the hot spot in execution time.
For 100 x 20 fields I really won't expect more than a second but it takes significant much more time. Is there any heal for this ?
Update
I have overseen some BLOB data that is returned. Thank you all.
You better use Jackson2
https://github.com/FasterXML/jackson
Java EE 7 has also a new JSON processing API, brand new!
http://docs.oracle.com/javaee/7/api/javax/json/package-summary.html
Profiling the different libs will provide answers. For enterprise applications, I never use GSON.
If you want to write benchmarks, use JMH. Writing high quality benchmarks isn't easy and JMH does a lot of the heavy lifting for you (although there are still a few gotchas).
If you wonder which Java Json library serializes/deserializes faster for various payload sizes, you can look at this extensive benchmark which compares a dozen of them with JMH. Fasted is dsljson, second is jackson. Gson is actually pretty slow for a 'modern' lib.

Need a real simple way to read json value in java

I am currently writing an application in Java, and am struggling to extract the values from a String which is in a JSON format.
Could someone help me with the easiest, most simplest way to extract data from this string? I'd prefer not to use external library if at all possible.
{"exchange":{"status":"Enabled","message":"Broadband on Fibre Technology","exchange_code":"NIWBY","exchange_name":"WHITEABBEY"},"products":[{"name":"20CN ADSL Max","likely_down_speed":1.5,"likely_up_speed":0.15,"availability":true....
Could someone explain how I could return the "likely down speed" of "20CN ADSL Max for example?
Thanks
Currently , there is no way in Java to parse json without an external lib (or your own implementation).
The org.json library is a standard when working with JSON.
You can use this snippet along with the library to achieve what you asked:
JSONObject obj = new JSONObject(" .... ");
JSONArray arr = obj.getJSONArray("products");
for (int i = 0; i < arr.length(); i++) {
String name = arr.getJSONObject(i).getString("name");
if ( name.equals("20CN ADSL Max") ) {
String s = arr.getJSONObject(i).getString("likely down speed");
}
}
Hope this helps.
For sure it's possible to do the parsing yourself, but it'll be much faster if you rely upon an existing library such as org.json.
With that, you can easily convert the string into a JSON object and extract all the fields you need.
If an existing library is not an option, you'll need to build yourself the tree describing the object in order to extract the pair key-values
While this may seem like a very simple, straightforward task, it gets rather complicated rather quickly.
Check out the SO thread How to parse JSON in Java. There is unfortunately not a single, clear solution to that question as shown in that thread. But I guess the org.json library seems to be the most popular solution.
If your application needs to handle arbitrary JSON, I would advise against trying to build your own parser.
Whatever your objections are to using an external library, get over them.

Efficient transcoding of Jackson parsed JSON

I'm using Jackson streaming API to deserialise a quite large JSON (on the order of megabytes) into POJO. It's working fine, but I'd like to optimize it (both memory and processing wise, code runs on Android).
The main problem I'd like to optimize away is converting a large number of strings from UTF-8 to ISO-8859-1. Currently I use:
String result = new String(parser.getText().getBytes("ISO-8859-1"));
As I understand it, parser originally copies token content into String (getText()), then creates a byte array from it (getBytes()), which is then used to create a final String in desired encoding. Way too much allocations and copying.
Ideal solution would be if getText() would accept the encoding parameter and just give me the final string, but that's not the case.
Any other ideas, or flaws in my thinking?
You can use:
parser.getBinaryValue() (present on version 2.4 of Jackson)
or you can implement an ObjectCodec (with a method readValue(...) that knows converting bytes to String in ISO8859-1) and set it using parser.setCodec().
If you have control over the json generation, avoid using a charset different than UTF-8.

parsing json java

I have a json data that I need to be parse in java The data is in the form
["string1","string2","string3",...]
Any idea how I can do that?
You can use JacksonJSON. For a good tutorial, have a look here.
You can use GSON api and use the code as below
Type type = new TypeToken<Collection<String>>(){}.getType();
List<String> results = new Gson().fromJson(json, type);
http://code.google.com/p/google-gson/
It depends a bit on how complete you want toe JSON parsing to be. If the above example is representative of all you expect, you might as well do some good old string parsing with indexOf and split.
If you want more complete JSON parsing, I'd suggest looking at the official json.org site and their Java page

JSON-lib escaping / preserving strings

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.

Categories