Michal
Michal

Reputation: 11

json problem java

I have a something like this

String value={"name":"Michal","location":"unknown"}

I would like to get all elements using JSONOBJECT

Something like this doesn't work:

JSONObject json = (JSONObject)new JSONParser().parse(value);        
System.out.println(json.get("name"))

Upvotes: 0

Views: 209

Answers (4)

Michal
Michal

Reputation: 11

I have solved this problem I think that the problem was with encoding now I use URLConnection and it works:

public class Json {
    public static JSONObject getJSON(String address) throws MalformedURLException, IOException, ParseException{

    URL url=new URL(address);
    URLConnection connection=url.openConnection();
    connection.connect();
    Scanner in=new Scanner(connection.getInputStream());
    StringBuilder sb=new StringBuilder();
    while (in.hasNextLine()){
        sb.append(in.nextLine());
    }
    String value=sb.toString();
    JSONObject json = (JSONObject)new JSONParser().parse(value);

    return json;

    }
}

Upvotes: 0

Michal
Michal

Reputation: 11

I get this from server http://localhost:4567/resource.json when I do value.toString() i excatly get what I wrote above.

I have got code:

in = new BufferedInputStream(new URL(address).openStream());
//    fout = new FileOutputStream(budaPath + destination);

byte data[] = new byte[1024];
int count;
while ((count = in.read(data, 0, 1024)) != -1)
{
    System.out.println(" "+data);
    //fout.write(data, 0, count);
}

String value = new String(data);
System.out.println(value);

Upvotes: 1

kamaci
kamaci

Reputation: 75257

Are you sure that you defined your string variable correct?

String name = "Michal";
String location = "unknown";
String value="{\"name\":\"" + name + "\", \"location\":\"" + unknown + "\"}"

Upvotes: 0

nicholas
nicholas

Reputation: 64

You can try this method。

    JSONObject json=JSONObject.fromObject(object)

If it's have some exceptions.Pls paste them.

Upvotes: 0

Related Questions