gpt4 book ai didi

java - 为什么原始数组不允许添加到 GSON 中的 JSON 结构

转载 作者:行者123 更新时间:2023-11-29 03:24:09 34 4
gpt4 key购买 nike

我想这样做来创建一个如下所示的 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/

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