1
votes

I have a web service that accepts a JSON and I use GSON to convert the JSON string into a POJO.

POJO Example:

class POJO{
    AtomicReference<String> property;       
}

JSON string example:

{"property":"val"}

However when the JSON string gets parsed by GSON, it throws a JSONSyntaxException because it expects the JSON string to be:

{"property":{"value":"val"}}

Do I just have to write a counterpart of the POJO (POJO2) with non-concurrent variables and then initialize my POJO (POJO1) with concurrent variables by using the POJO2 values? Or, is there a way to make GSON to treat the AtomicReference variable as a String?

If I do the former, it takes away the feature of GSON to output an object from a json string on the fly.

1
you need to also write POJO for fields of AtomicReferenceOnkar
What do you mean?Jin

1 Answers

1
votes

I consulted Google again and found this answer of making TypeAdapters. So, I rolled my own type adapter for it. I also use other Atomic objects like AtomicLong in my POJO class and this approach also worked for it.

class AtomicStringTypeAdapter extends TypeAdapter<AtomicReference<String>> {

    @Override
    public AtomicReference<String> read(JsonReader in) throws IOException {

        AtomicReference<String> value = null;

        JsonParser jsonParser = new JsonParser();
        JsonElement je = jsonParser.parse(in);

        if (je instanceof JsonPrimitive) {
            value = new AtomicReference<String>();
            value.set(((JsonPrimitive) je).getAsString());
        } else if (je instanceof JsonObject) {
            JsonObject jsonObject = (JsonObject) je;
            value = new AtomicReference<String>();
            value.set(jsonObject.get("value").getAsString());
        }

        return value;
    }

    @Override
    public void write(JsonWriter out, AtomicReference<String> value) throws IOException {
        if (value != null) {
                out.beginObject();
                out.name("value").value(value.get());
                out.endObject();
        }
    }
}