2

I cannot get a value from a key, because the key has a $ in it. Here is the jsonobject:

JSONParser parser = new JSONParser();
String str = "{\"$oid\":\"5168d0e0b280f084c3742800\"}";
JSONObject obj = (JSONObject)parser.parse(str);

String oid = (String) obj.get("$oid");
System.out.println("oid: " + oid);

However the output is:

oid: null

How can I deal with the key with a special character $ in it?

Li'
  • 3,133
  • 10
  • 34
  • 51

2 Answers2

1

The string str is not being formed properly. You need to escape the quotes. Try this:

String str = "{\"$oid\":\"5168d0e0b280f084c3742800\"}";
shiladitya
  • 2,290
  • 1
  • 23
  • 36
  • I am sorry. Actually it works. It is my mistake to got the wrong json object. Thx – Li' Apr 21 '13 at 01:19
0

This worked. But I did not use JSONParser.

    String str = "{\"$oid\":\"5168d0e0b280f084c3742800\"}";
    JSONObject obj;
    try 
    {
        obj = new JSONObject(str);
        String oid = (String) obj.get("$oid");
        System.out.println("oid: " + oid);
        Toast.makeText(this, oid, Toast.LENGTH_SHORT).show();

    } 
    catch (JSONException e) {
        e.printStackTrace();
    }
shiladitya
  • 2,290
  • 1
  • 23
  • 36