Search code examples
javajsonparsingjacksonobjectmapper

Fastest way to parse single value from JSON string


I have a string that I get from a websocket in the below JSON format. I want a very low-latency way to parse the value c associated with the key C. The key names are the same for every packet I get, but the values may differ. So, the key C will stay the same but the value can change from c to something perhaps longer. In my real life application, the number of entries inside X and Y can be much longer.

I've tried a few different approaches, including parsing a single field using Jackson [1], to parsing the full string to JsonNode, but they're all too slow (over 50 microseconds). I thought of finding the position in the String of "C" using [2], and then taking the next few characters after that, but the issue is that the value, c, is variable length so that makes it tricky.

String s = {"A":"a","B":"b","data":[{"C":"c","X":[["3.79","28.07","1"],["3.791","130.05","3"],["3.792","370.8958","5"]],"Y":[["3.789","200","1"],["3.788","1238.1709","4"],["3.787","513.4051","3"]]}'

I'd like something like this:

String valueOfC = getValueOfC(s) // return in only a few microseconds

[1] How to read single JSON field with Jackson

[2] Java: method to get position of a match in a String?


Solution

  • s.substring(s.indexOf("\"data\":[{\"C") + 4, s.indexOf("\"",s.indexOf("\"data\":[{\"C") + 4)));
    

    This is sub-microsecond.