0

is there any easy way to to convert this json:

{
    ...,
    "pictures": [
        "url1",
        "url2"
    ],
    ...
}

to

List<Picture> pictures

where Picture is:

class Picture{
      String url;
}

It won't work as above, because I have an exception, saying

Expected BEGIN_OBJECT but was STRING
2
  • A quick fix depending on your use of the object could be to put @JsonValue above the getter for your String url. Commented Jul 14, 2016 at 15:40
  • @Zircon Wrong library. Also, that would only be useful for serializing. Commented Jul 14, 2016 at 15:47

1 Answer 1

1

You need to implement a custom deserializer for this. Should be looking like this (I didn't try to execute, but that should give you the idea where to start, presumably you have a public constructor with String argument in your Picture.class)

private class PictureDeserializer implements JsonDeserializer<Picture> {
  public Picture deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
      throws JsonParseException {
    return new Picture(json.getAsJsonPrimitive().getAsString());
  }
}

It should be registered:

GsonBuilder gson = new GsonBuilder();
gson.registerTypeAdapter(Picture.class, new PictureDeserializer());
Sign up to request clarification or add additional context in comments.

3 Comments

I know deserializer method to do this thing, is there any other way to avoid making deserializer?
@PaleNisko Then you should mention it in the question to avoid making people to waist time. Anyway, the answer: I don't think so. The mapper contains a predefined set of actions mapped to the most generic types/classes on one-to-one relationship basis (simplified). Going through JSON tree, the mapper encounters different types/classes and deserializes them accordingly. E.g. single string is mapped to the String.class out-of-box. If you have a custom Picture.class, the mapper just cannot have the consistent mapping out-of-box as its developers couldn't keep in mind all classes in the world.
Ok, thank you for your feedback i will keep in mind your advice. Know I understand why it is done like that!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.