0

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

FMC
  • 650
  • 12
  • 31
  • 3
    `I'd prefer not to use external library if at all possible` Is there a reason for this? – Tom Nov 01 '14 at 15:09
  • possible duplicate of [How to parse JSON in Java](http://stackoverflow.com/questions/2591098/how-to-parse-json-in-java) – trooper Nov 01 '14 at 15:47

3 Answers3

0

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

mbera
  • 21
  • 2
0

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.

Protostome
  • 5,569
  • 5
  • 30
  • 45
0

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.

Community
  • 1
  • 1
helmy
  • 9,068
  • 3
  • 32
  • 31