0

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"))
4
  • does not work how? Do you get any errors? Commented Mar 10, 2011 at 8:21
  • Post your stacktrace please, besides the string value is not proper java syntax. Commented Mar 10, 2011 at 8:22
  • 2
    String value={"name":"Michal","location":"unknown"} -- that can't possibly be right. Commented Mar 10, 2011 at 8:23
  • 1
    The String value isn't legal syntax - what do you actually have? Commented Mar 10, 2011 at 8:24

4 Answers 4

1

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);
Sign up to request clarification or add additional context in comments.

Comments

0

You can try this method。

    JSONObject json=JSONObject.fromObject(object)

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

1 Comment

when value.toString() I have got exacty:
0

Are you sure that you defined your string variable correct?

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

Comments

0

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;

    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.