Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get a specific value from JSON string

Tags:

java

json

//Open url and fetch JSON data
String s = "MY_URL_HERE";
URL url = new URL(s);
Scanner scan = new Scanner(url.openStream());
String str = new String();
while (scan.hasNext())
{
    str += scan.nextLine();
}
scan.close();

System.out.println(str);

str will print a string like :

{"coord":{"lon":-80.25,"lat":43.55},"weather":[{"id":800,"main":"Clear","description":"Sky is Clear","icon"...ect

I am using json_simple-1.1.jar

How do I actually use this string to extract values of my choosing? If i wanted to pull out the "description" or the "weather".

I have tried snippets from:

https://code.google.com/p/json-simple/wiki/DecodingExamples

These do not work for me, I get an error

org.json.simple.JSONObject cannot be cast to org.json.simple.JSONArray
like image 396
Dimitrije M Avatar asked Apr 07 '26 21:04

Dimitrije M


1 Answers

Your string is not ant json array representation but json object itself . Thats what error org.json.simple.JSONObject cannot be cast to org.json.simple.JSONArray depicts. Example in your link describes an array, and each element of that array is an object:

Consider Jackson libray which is very convenient for converting Java object to / from JSON

Below represent an array, and each element of that array is an object:

[
    {
        color: "red",
        value: "#f00"
    },
    {
        color: "green",
        value: "#0f0"
    }
]

or

[
    {
        "color": "red",
        "value": "#f00"
    },
    {
        "color": "green",
        "value": "#0f0"
    }
]

Below represent the object

{
    color: "red",
    value: "#f00"
}

or

{
    "color": "red",
    "value": "#f00"
}

See here for different representation of json string

Code sample using jackson library

import java.io.IOException;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;


public class TestString {

    public static void main(String[] args) throws JsonParseException, JsonMappingException, IOException {

        String s="{\"coord\":{\"lon\":-80.25,\"lat\":43.55},\"weather\":[{\"id\":800,\"main\":\"Clear\",\"description\":\"Sky is Clear\"}]}";
        //String s="[{\"coord\":\"test\",\"lon\":-80.25}]";
        ObjectMapper mapper = new ObjectMapper();
        Object obj = mapper.readValue(s, Object.class );
        System.out.println("terst"+ obj );
    }

}
like image 110
M Sach Avatar answered Apr 10 '26 12:04

M Sach



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!