我有以下 Java 类
public static class LogItem {
public Long timestamp;
public Integer level;
public String topic;
public String type;
public String message;
}
我想转换 ArrayList<LogItem>
转换为以下 JSON 字符串:
{"logitems":[
{"timestamp":1560924642000, "level":20, "topic":"websocket", "type":"status", "message":"connected (mobile)"},
...
]}`
我想执行以下操作:
JSONArray logitems = new JSONArray();
for (DB_LogUtils.LogItem item : items) {
logitems.put(DB_LogUtils.asJSONObject(item)); // <----
}
JSONObject data = new JSONObject();
data.put("logitems", logitems);
webViewFragment.onInjectMessage(data.toString(), null);
哪里DB_LogUtils.asJSONObject
就是下面的方法
public static JSONObject asJSONObject(LogItem item) throws JSONException
{
JSONObject logitem = new JSONObject();
logitem.put("timestamp", item.timestamp);
logitem.put("level", item.level);
logitem.put("topic", item.topic);
logitem.put("type", item.type);
logitem.put("message", item.message);
return logitem;
}
但我不想手动执行此操作(如 logitem.put("timestamp", item.timestamp);
),而是想使用 Gson
执行此操作,这样我最终会得到这样的结果
JSONArray logitems = new JSONArray();
for (DB_LogUtils.LogItem item : items) {
logitems.put(new Gson().toJSONObject(item)); // <----
}
JSONObject data = new JSONObject();
data.put("logitems", logitems);
webViewFragment.onInjectMessage(data.toString(), null);
以便在 LogItem 类更改时不必在多个点编辑代码。
但是Gson().toJSONObject(...)
不存在,仅Gson().toJson(...)
,它返回 String
。我不想转变为String
然后用 org.json.JSONObject
解析它.
我最终使用了第二类
public static class LogItems {
public List<LogItem> logitems = new ArrayList<>();
}
然后让我将整个代码更改为
webViewFragment.onInjectMessage(new Gson().toJson(items), null);
哪里items
类型为 LogItems
.
在这种情况下,创建额外的包装类是一个整体好处,但我仍然想知道如何使用 Gson 从类创建这样的 JSONObject。
最佳答案
据我所知,如果不使用 for 循环将 json 字符串迭代到数组中并使用相同的键存储到 map 中,这是不可能的。
但是您可以实现您的解决方案,而不是传递 d 将项目列表传递到 gson 对象,如下所示。
List<Object> list = new ArrayList<Object>();
list.add("1560924642000");
list.add(20);
list.add("websocket");
list.add("status");
list.add("connected (mobile)");
Gson gson = new Gson();
Map mp = new HashMap();
mp.put("ietams", list);
String json = gson.toJson(mp);
System.out.println(json);
输出将是
{"logitems":["1560924642000",20,"websocket","status","connected (mobile)"]}
希望这会有所帮助!
关于java - 使用 Gson 从类对象创建 org.json.JSONObject,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56661362/