java - 如何在 Java 中使用 JSON Simple 创建 JSON
问题描述
我有以下 json 字符串,我想将其转换为 java 代码,以便更轻松地更改它并发送更新的请求,但我似乎无法弄清楚如何使用JSONObject
和生成它JSONArray
。
["guest_login",{"chips":{"1":2000},"epoch":1552509677,"invested":{"1":2000},"login_id":10,"news":["Welcome to Poker.","Register and get started with 2000 play chips."],"username":"Guest10"}]
我得到以下输出
output = ["guest_login",null,null]
这是我到目前为止所尝试的。
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
JSONObject obj = new JSONObject();
JSONArray list = new JSONArray();
list.add("guest_login");
list.add(new JSONObject().put("chips", new JSONObject().put("1", "2000")));
list.add(obj.put("epoch", "1552509677"));
System.out.println("output = " + list.toString());
也试过
JSONObject json = new JSONObject();
json.put("name", "student");
JSONArray array = new JSONArray();
JSONObject item = new JSONObject();
item.put("invested", new JSONObject().put("1", "2000"));
item.put("login_id", "10");
item.put("epoch", "1552509677");
item.put("chips", new JSONObject().put("1", "2000"));
item.put("news", new JSONArray().add("Welcome to Poker.").add("Register and get started with 2000 play chips."));
item.put("username","Guest10");
json.put("guest_login", new JSONArray().add(item));
message = json.toString();
System.out.println("output = " + message);
解决方案
我只是运行此代码并且工作正常,只需更改不同的库:
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
...
JSONObject obj = new JSONObject();
JSONArray list = new JSONArray();
list.put("guest_login");
try {
list.put(new JSONObject().put("chips", new JSONObject().put("1", "2000")));
list.put(obj.put("epoch", "1552509677"));
} catch (JSONException e) {
e.printStackTrace();
}
修复了它在下面使用此代码完美无缺!
list.put("guest_login");
try {
obj.put("chips", new JSONObject().put("1", "2000"));
obj.put("invested", new JSONObject().put("1", "2000"));
obj.put("login_id", "10");
JSONArray news = new JSONArray();
news.put("Welcome to Poker.");
news.put("Register and get started with 2000 play chips.");
obj.put("news", news);
obj.put("username","Guest10");
obj.put("epoch", "119677");
list.put(obj);
} catch (JSONException e) {
e.printStackTrace();
}
推荐阅读
- javascript - 从 Javascript 打开包含空间的 chrome 路径
- rocket-chip - 为什么“def”用于定义火箭芯片某些部分的常数?
- lyx - LyX:将子文档作为输入插入时,确定按钮显示为灰色
- laravel - 我可以在 CLI 中的一个条目中运行 Laravel Tinker 中的命令吗?
- html - 如何识别不同的车把模板?
- django - 使用 Django REST 和 AngularJS 的邮递员
- python - 我如何从 for 循环中获取输入并将其添加到循环的第二个输入中
- android - 如何在android的http请求中使用时钟数据?
- node.js - 如何解决无法连接,因为 '1' 专用管理员连接的最大数量已经存在于 sql 中?
- authentication - Symfony 4 角色管理