gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 06:44:47 25 4
gpt4 key购买 nike

我正在使用 gson 将 JSON 映射到 Java 对象上。我有类似于下面示例的 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 中的所有其他字段,也没有省略我不需要的“节点”,比如元等?或者我需要为我正在获取的 JSON 中的所有字段创建对象,即使我不会在我的代码中使用它们?

最佳答案

是的,省略您希望忽略的属性是完全可以的。

事实上,如果您不需要值,则不应为其包含属性,如果有的话,它会为您提供更好的性能。

关于java - 如何使用 gson 将选定字段从 JSON 映射到 Java 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27325995/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com