我想这样做来创建一个如下所示的 json 对象。
JsonObject request = new JsonObject();
request.addProperty("requestid", UUID.randomUUID().toString());
request.addProperty("type", "hotel");
request.addProperty("markups", new double[]{1.0,2.0,3.0}); // This says "The method addProperty(String, String) in the type JsonObject is not applicable for the arguments (String, double[])"
request.add("markups", new double[]{1.0,2.0,3.0});// This says "The method add(String, JsonElement) in the type JsonObject is not applicable for the arguments (String, double[])"
JSON 对象:
{
"requestid": "05afcd81-9c59-4a21-a61e-ae48fda6bdd0",
"type": "hotel",
"markups": [1.0,2.0,3.0]
}
请注意,这不是关于 fromJson 和 toJson 的事情。它是 JSON 创建和读取对象而不是转换。 那么,我该如何使用上述实现呢。
最佳答案
由于您想使用解析树对象来构建您的 JSON 结构,您需要实例化并将值添加到 JsonArray
对象,或者使用 Gson 并转换您的 double[ ]
。我假设您宁愿选择后者:
public static void main( String[] args )
{
double[] d = new double[] { 1.0, 2.0};
JsonElement e = new Gson().toJsonTree(d);
JsonObject o = new JsonObject();
o.add("array", e);
System.out.println(o);
}
输出:
{"array":[1.0,2.0]}
toJsonTree()
方法获取您的 Java 数组并将其转换为 Gson 解析树 JsonArray
并将其作为父类(super class) JsonElement
返回
关于java - 为什么原始数组不允许添加到 GSON 中的 JSON 结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21965469/