Li'
Li'

Reputation: 3183

Json how to get value from key with special character - json-simple

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?

Upvotes: 2

Views: 2594

Answers (2)

shiladitya
shiladitya

Reputation: 2310

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();
    }

Upvotes: 0

shiladitya
shiladitya

Reputation: 2310

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

String str = "{\"$oid\":\"5168d0e0b280f084c3742800\"}";

Upvotes: 1

Related Questions