[英]Creating a json with multiple data type?
I have a requirement that I have to create a Json which look like this我有一个要求,我必须创建一个看起来像这样的 Json
{
"method": "Main",
"executeTime": 4,
"arguments": [
{
"input": "input param"
},
{
"output": "output string"
}
],
"error": null
}
Since it have multiple data types inside, so I made a hash map to handle them as objects, then I could use GSON.toJson()
to get what I need.由于它内部有多种数据类型,所以我做了一个 hash map 将它们作为对象处理,然后我可以使用
GSON.toJson()
来获得我需要的东西。 Here's my code这是我的代码
HashMap<String, Object> firstLayer = new HashMap<String, Object>();
HashMap<String, Object> secLayer = new HashMap<String, Object>();
List<HashMap<String, Object>> list = new ArrayList<HashMap<String, Object>>();
firstLayer.put("error", null);
firstLayer.put("method", <method String>);
firstLayer.put("executeTime", System.currentTimeMillis() - beginTime);
secLayer.put("input", <input param string>);
list.add(secLayer);
secLayer = new HashMap<String, Object>();
secLayer.put("output", <output string>);
list.add(secLayer);
// JIT pops error here. This is unexpected.
firstLayer.add("arguments", list);
Error msg say: The method add(String, List<HashMap<String,Object>>) is undefined for the type HashMap<String,Object>
.错误消息说:
The method add(String, List<HashMap<String,Object>>) is undefined for the type HashMap<String,Object>
。 Even tried to use cast like firstLayer.add("arguments", (Object)list);
甚至尝试使用像
firstLayer.add("arguments", (Object)list);
这样的强制转换but it still not right.但它仍然不对。 Any other option or walkaround?
还有其他选择或绕行吗?
I got it wrong, it is not firstLayer.add("arguments", list);
我弄错了,它不是
firstLayer.add("arguments", list);
but firstLayer.put("arguments", list);
但是
firstLayer.put("arguments", list);
I think I worked too hard today.我觉得我今天太努力了。 Thanks #tevemadar
谢谢#tevemadar
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.