繁体   English   中英

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

[英]Create org.json.JSONObject from a class object by using 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字符串迭代到数组并使用相同的键存储到映射中,则无法实现。

但是你可以实现你的解决方案而不是传递dto将项目列表传递到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)"]}

希望这会有所帮助!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM