开发者

Android JSON/GSON deserialization problem

I am trying od deserialize the following JSON part with GSON.

       "images": [
        {
         "link": "http://media.neckermann.de/image/101/900/7/27/927/101_219927.jpg"
        },
        {
         "link": "http://media.neckermann.de/image/101/480/7/27/927/101_219927.jpg"
        },
        {
         "link": "http://media.neckermann.de/image/101/210/7/27/927/101_219927.jpg"
        }
       ]

If GSON gets this JSON string, GSON crashes. If there is only one item in "images" it works great. How can I fix that problem开发者_开发问答? Sometimes I get only one "link" in JSON and sometimes there are three entries in JSON like above. How can I handle this JSON with GSON?

Thanks a lot in advance!

Martin


The output of the following example is

[link=http://media.neckermann.de/image/101/900/7/27/927/101_219927.jpg, 
link=http://media.neckermann.de/image/101/480/7/27/927/101_219927.jpg, 
link=http://media.neckermann.de/image/101/210/7/27/927/101_219927.jpg]
public class Foo
{
  static String jsonInput = 
    "{" + 
      "\"images\":" + 
      "[" + 
        "{" + 
          "\"link\":\"http://media.neckermann.de/image/101/900/7/27/927/101_219927.jpg\"" + 
        "}," + 
        "{" + 
          "\"link\":\"http://media.neckermann.de/image/101/480/7/27/927/101_219927.jpg\"" + 
        "}," + 
        "{" + 
          "\"link\":\"http://media.neckermann.de/image/101/210/7/27/927/101_219927.jpg\"" + 
        "}" + 
      "]" + 
    "}";

  public static void main(String[] args)
  {
    GsonBuilder gsonBuilder = new GsonBuilder();
    gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES);
    Gson gson = gsonBuilder.create();
    ImageUris uris = gson.fromJson(jsonInput, ImageUris.class);
    System.out.println(uris);
  }
}

class ImageUris
{
  private ImageUri[] images;

  @Override
  public String toString()
  {
    return Arrays.toString(images);
  }
}

class ImageUri
{
  private String link;

  @Override
  public String toString()
  {
    return "link=" + link;
  }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜