自定义使用GSON解析JSON字段

时间:2015-08-20 12:04:46

标签: java android json gson

我关注json

{
    "id": 1,
    "title": "Title blabla",
    "thing": {
        "field1": 1,
        "field2": "field2",
        "etc": "etc.."
    }
}

和模型

public class MyModel {
    private int id;
    private String title;
    private String thing;
}

我用gson

解析它
 Gson gson = new Gson();
 MyModel myModel = gson.fromJson(json, type);

并希望实现结果:

myModel.id -> 1
myModel.title -> "Title blabla"
myModel.thing-> "{
              "field1": 1,
              "field2": "field2",
              "etc": "etc.."
             }"

换句话说,我不希望某些字段被反序列化,而是保留为原始的相应json字符串。

如何使用gson实现此目的?

4 个答案:

答案 0 :(得分:2)

您可以将事物更改为Map,然后更改为toString(),以生成您正在寻找的结果。

答案 1 :(得分:2)

您可以实现自己的序列化程序和desirializer,例如,请参阅here

答案 2 :(得分:1)

如果要解析类似的JSON对象,则必须使用内部类,例如尝试此操作:

this

答案 3 :(得分:1)

您可以将String更改为Object,以便将其解除/序列化为相同的JSON字符串。看起来像这样:

import com.google.gson.Gson;

public class Answers {
    public static void main(String[] args) {
        String json = "{" 
                + "    \"id\": 1,"
                + "    \"title\": \"Title blabla\"," + "    \"thing\": {"
                + "        \"field1\": 1," + "        \"field2\": \"field2\","
                + "        \"etc\": \"etc..\"" + "    }" 
                + "}";
        Gson gson = new Gson();
        MyModel myModel = (MyModel) gson.fromJson(json, MyModel.class);
        System.out.println(gson.toJson(myModel));

    }

    class MyModel {
        private int id;
        private String title;
        private Object thing;
    }

}

输出:

{"id":1,"title":"Title blabla","thing":{"field1":1.0,"field2":"field2","etc":"etc.."}}