java - 使用 Gson 从类对象创建 org.json.JSONObject

标签 java json gson

我有以下 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/

相关文章:

java - 自定义 View 和 ImageView 之间的像素完美碰撞检测

java - 如何自动化 Rust 代码的 Java 绑定(bind)?

javascript - 我的函数不会返回要保存在数组中的对象

json - Gson fromJson 解析嵌套json

java - 服务 POWER_CONNECTED 和 POWER_DISCONNECTED。是否可以?

java - 在 Web 应用程序中运行 ScheduledExecutorService 是否有任何影响

java - 处理 JSON 更改信息的最佳方式

JSONValue 到缩进字符串

android - Gson 忽略 json 字段并反序列化

java - 我应该为 Servlet 的所有 doGet/doPost 调用实例化一个共享 Gson 对象吗?