java Gson,创建一个简单的 JsonObjects JsonArray
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36634140/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Gson, creating a simple JsonArray of JsonObjects
提问by Allen G
I'm trying to build a JsonArray of JsonObjects using gson. Each JsonObject will take the following format,
我正在尝试使用 gson 构建一个 JsonObjects 的 JsonArray。每个 JsonObject 将采用以下格式,
{"image":"name1"}
{"image":"name2"}
and so on.
等等。
I have a string array of the names ("name1","name2",...) I cannot convert string array directly in to a JsonArray. I'm trying to create JsonObjects iteratively and add it to a JsonArray.
我有一个名称的字符串数组(“name1”,“name2”,...)我无法将字符串数组直接转换为 JsonArray。我正在尝试以迭代方式创建 JsonObjects 并将其添加到 JsonArray。
JsonObject innerObject;
JsonArray jArray = new JsonArray();
for(int i = 0; i<names.length; i++)
{
innerObject = new JsonObject();
innerObject.addProperty("image",names[i]);
jArray.add(innerObject);
}
But as I understand, add
method in JsonArray takes a JsonElement and here I'm giving a JsonObject. I couldn't find a way to convert JsonObject to JsonElement.
The whole point of using gson will be gone when I do this. Is there a better way?
但据我所知,add
JsonArray 中的方法需要一个 JsonElement,这里我给出了一个 JsonObject。我找不到将 JsonObject 转换为 JsonElement 的方法。当我这样做时,使用 gson 的全部意义将消失。有没有更好的办法?
采纳答案by meda
If you are going to use GSON use it like this to convert to object
如果您打算使用 GSON,请像这样使用它来转换为对象
List<Image>images = new Gson().fromJson(json, Image[].class);
To get json string
获取json字符串
String json = new Gson().toJson(images);
That's the point of gson you should not manipulate the data with loops and stuff. You need to take advantage of its powerful model parsing.
这就是 gson 的重点,你不应该用循环和东西来操作数据。您需要利用其强大的模型解析功能。
回答by Allen G
First, create a class that represents a single json object, e.g.:
首先,创建一个表示单个 json 对象的类,例如:
class MyObject {
private String image;
public MyObject(String name) { image = name; }
}
Gson will use the class' variable names to determine what property names to use.
Gson 将使用类的变量名称来确定要使用的属性名称。
Then create an array or list of these using the data you have available, e.g.
然后使用您可用的数据创建一个数组或这些列表,例如
ArrayList<MyObject> allItems = new ArrayList<>();
allItems.add(new MyObject("name1"));
allItems.add(new MyObject("name2"));
allItems.add(new MyObject("name3"));
Finally, to serialize to Json, do:
最后,要序列化为 Json,请执行以下操作:
String json = new Gson().toJson(allItems);
And to get the data back from json
to an array:
并将数据从json
数组中取回:
MyObject[] items = new Gson().fromJson(json, MyObject[].class);
For simple (de)serialization, there is no need to be dealing directly with Json classes.
对于简单的(反)序列化,不需要直接处理 Json 类。