I'm parsing some JSON received from a REST service call using Java streams JsonParser.getObjectStream()
, and filtering for particular values, but was never getting a match where I was expecting one. Digging deeper, I found that the string values being returned containing extra double-quotes at the beginning and end.
Here's some code to illustrate. First I show the "direct" method of getting values, then the streams method.
package com.company.jsonptest;
import java.io.StringReader;
import javax.json.Json;
import javax.json.JsonObject;
import javax.json.stream.JsonParser;
public class GetStringTest {
public static void main(String[] args) {
System.out.println("Direct...");
JsonParser parser = Json.createParser(new StringReader(json));
parser.next();
JsonObject jsonObject = parser.getObject().asJsonObject();
String username = jsonObject.getString("firstname");
String name = jsonObject.getString("lastname");
System.out.println("firstname: " + username);
System.out.println("lastname: " + name);
System.out.println("Streams...");
JsonParser parser2 = Json.createParser(new StringReader(json));
parser2.next();
parser2.getObjectStream().forEach(entry -> {
String key = entry.getKey();
String value = entry.getValue().toString();
String type = entry.getValue().getValueType().toString();
System.out.println(key + ": " + value + " (" + type + ")");
});
}
private static String json = "{n"
+ " "firstname": "John",n"
+ " "lastname": "Smith"n"
+ "}";
}
Here's the output. Notice the extra quotes. I've included the JsonValue type as an extra check.
Direct...
firstname: John
lastname: Smith
Streams...
firstname: "John" (STRING)
lastname: "Smith" (STRING)
Is there a way to get around this, apart from adding an extra step to strip off the quotes?