如何使用gson将选定的字段从JSON映射到Java对象

时间:2014-12-05 22:54:01

标签: java json gson

我正在使用gson在Java对象上映射JSON。我的JSON看起来类似于下面的示例

{
    "meta": {
        "status": 200,
        "msg": "OK"
    },
    "response": {
        "blog": {
            "title": "We have the Munchies.",
            "name": "wehavethemunchies",
            "posts": 10662,
            "url": "http://wehavethemunchies.tumblr.com/",
            "updated": 1415895690,
            "description": "<p>If any of you have any tasty recipes you wanna share just click submit~ If you are the owner of one of the images and wish to have it removed please message us and we will remove it quickly. Sorry for the inconvenience. </p>\n\n<p> If anything is tagged <strong>recipe</strong>, you can click through to the photos link for the recipe. If it is a flickr image, click through to the flickr image for a link directly to the recipe.\n<p><strong>Here are our most popular tags:</strong><p>\n\n<p><a href=\"http://wehavethemunchies.tumblr.com/tagged/munchies\">Got the munchies?</a>\n<p><a href=\"http://wehavethemunchies.tumblr.com/tagged/Recipe\">Recipe</a>\n<p><a href=\"http://wehavethemunchies.tumblr.com/tagged/Pizza\">Pizza</a>\n<p><a href=\"http://wehavethemunchies.tumblr.com/tagged/Breakfast\">Breakfast</a>\n<p><a href=\"http://wehavethemunchies.tumblr.com/tagged/Lunch\">Lunch</a>\n<p><a href=\"http://wehavethemunchies.tumblr.com/tagged/Dessert\">Dessert</a>\n<p><a href=\"http://wehavethemunchies.tumblr.com/tagged/chocolate\">Chocolate</a>\n<p><a href=\"http://wehavethemunchies.tumblr.com/tagged/nutella\">Nutella</a>\n<p><a href=\"http://wehavethemunchies.tumblr.com/tagged/vegan\">Vegan</a>\n<p>\n<small>-4/13/09</small>",
            "is_nsfw": false,
            "ask": true,
            "ask_page_title": "Ask me anything",
            "ask_anon": false,
            "submission_page_title": "Submit to your heart's content~",
            "share_likes": false
        }
    }
}

假设我只想要映射选定的字段,例如博客部分的标题和说明。为此,我创建了处理此请求的java类并创建了Blog对象,它有两个字段,表示JSON中的字段,我要映射

import java.io.Serializable;

import org.json.JSONObject;

import com.google.gson.Gson;

public class HomeResponse implements Serializable{

    public Blog blog;

    public static HomeResponse fromJsonObject(JSONObject jsonObject){
        Gson gson = new Gson();
        return gson.fromJson(jsonObject.toString(), HomeResponse.class);
    }

}

我要映射JSON的对象:

import java.io.Serializable;

import com.google.gson.annotations.SerializedName;

public class Blog implements Serializable{

    public String title;
    public String description;
}

我的问题是:我可以这样做吗?没有创建JSON中的所有其他字段,也省略了“节点”,我不需要像meta等?或者我需要为我正在获取的JSON中的所有字段创建对象,即使我不会在我的代码中使用它们?

1 个答案:

答案 0 :(得分:0)

是的,可以省略你想忽略的属性。

事实上,如果你不需要价值,你不应该为它包含一个属性,它会为你提供更好的表现。