Search code examples
javajsonjavax.json

Java JSON: get object-value without quotes?


I parse a JSON string. How can I get the value of an object without the quotes? I get it with lists but it is not working with objects.

import javax.json.*;
import javax.json.stream.*;

...

    String s="{ \"foo\" : [ \"abc\", \"def\" ],   \"bar\" : { \"k1\" : \"v1\", \"k2\" : \"v2\" } }";

    JsonReader jr = Json.createReader(new StringReader (s));
    JsonObject jo = jr.readObject();

    JsonArray foo = jo.getJsonArray ("foo");
    for (int i = 0; i < foo.size (); i ++)
    {
        System.out.println (i + ": " + foo.getString (i));  // ok, no quotes
    }

    JsonObject bar = jo.getJsonObject ("bar");
    for (Map.Entry <String, JsonValue> e : bar.entrySet ())
    {
        System.out.println (e.getKey() + ": " + e.getValue ().toString()); 
    }

Thats the output.

0: abc
1: def
k1: "v1"
k2: "v2"

How can I get v1 and v2 without quotes out of the parser?


Solution

  • You know your input value are String, so you can do this:

    for (Map.Entry <String, JsonValue> e : bar.entrySet ()) {
        System.out.println (e.getKey() + ": " + ((JsonString)e.getValue ()).getString()); 
    }