如何用GSON解析变量类型的json?

时间:2015-08-06 10:02:43

标签: java json gson

我记得那样的对象

{
  "data": "some data",
  "social": {
    "twitter": "id"
  }
}

使用下一个类

可以轻松解析
public class SocialLinks {

@Expose
private String data;
@Expose
private Social social;
}
public class Social {

@Expose
private String twitter;
}

不幸的是,由于某些问题,如果社交是空的,那么它将被视为数组

{
  "data": "some data",
  "social": [

  ]
}

如何用gson解析它? (我不是服务器端的开发人员,不能影响响应时间)

1 个答案:

答案 0 :(得分:1)

你可以使用这些类来做到这一点。

SocialLinks.java

public class SocialLinks {
    private String data;
    private Social social;
    // Getters && Setters
}

Social.java:

public class Social {

    private String twitter;
    // Getters & Setters
}

这是你的主要方法

public class GsonApp {

    private static final String TEST_JSON = "{\n" +
            "  \"data\": \"some data\",\n" +
            "  \"social\": {\n" +
            "    \"twitter\": \"id\"\n" +
            "  }\n" +
            "}";


    public static void main(String[] args) throws Exception {
        final Gson gson = new GsonBuilder().create();
        // Read Example
        final SocialLinks socialLinks = gson.fromJson(TEST_JSON, SocialLinks.class);
        System.out.println(gson.toJson(socialLinks));

        // Write with null Social 
        final SocialLinks socialLinks1 = new SocialLinks();
        socialLinks1.setData("MyData");
        System.out.println(gson.toJson(socialLinks1));

        // Write with empty Social (social.twitter is null)    
        final SocialLinks socialLinks2 = new SocialLinks();
        socialLinks2.setData("MyData");
        socialLinks2.setSocial(new Social());
        System.out.println(gson.toJson(socialLinks2));

        // Write with full Social
        final SocialLinks socialLinks3 = new SocialLinks();
        socialLinks3.setData("MyData");
        socialLinks3.setSocial(new Social());
        socialLinks3.getSocial().setTwitter("ID");
        System.out.println(gson.toJson(socialLinks3));
    }
}

这将输出

{"data":"some data","social":{"twitter":"id"}}
{"data":"MyData"}
{"data":"MyData","social":{}}
{"data":"MyData","social":{"twitter":"ID"}}

更新

如果根据应用程序状态更改数据类型,则可能需要创建Map对象而不是DTO。这是一个例子

private static final String TEST_JSON_2 = "{\n" +
        "  \"data\": \"some data\",\n" +
        "  \"social\": [\n" +
        "  ]\n" +
        "}";

...

    Type type = new TypeToken<Map<String, Object>>(){}.getType();
    final Map<String, Object> socialLinks4 = gson.fromJson(TEST_JSON_2, type);
    System.out.println(socialLinks4);

    final Map<String, Object> socialLinks5 = gson.fromJson(TEST_JSON, type);
    System.out.println(socialLinks5);

这将输出

{data=some data, social=[]}
{data=some data, social={twitter=id}}