1
我正在使用gson在Java對象上映射JSON。我有JSON看起來類似於下面的例子如何使用gson將所選字段從JSON映射到Java對象
{
"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類,處理該請求並創建博客對象,它有兩個字段,表示JSON領域,其中我要地圖上,我要地圖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);
}
}
對象:
import java.io.Serializable;
import com.google.gson.annotations.SerializedName;
public class Blog implements Serializable{
public String title;
public String description;
}
我的問題是:我可以這樣做嗎?如果不創建JSON中的所有其他字段,並且也省略「節點」,我不需要像元等。或者我需要爲所有字段創建對象,這些字段在我正在獲取的JSON中,即使我不會在代碼中使用它們。