java - 构建有序 JSON 字符串(GSON 库)
问题描述
下面是我的 JSON 应该是什么样子的一个简单示例。该对象具有名字和姓氏的字符串值、年龄的数字值和电话号码对象的数组值。
{
"firstName": "John",
"lastName": "Smith",
"age": 25,
"phoneNumbers": [
{
"type": "home",
"number": "212 555-1234"
},
{
"type": "fax",
"number": "646 555-4567"
}
]
}
这是我的代码:
// creating JSONObject
JSONObject jsonObj = new JSONObject();
// putting data to JSONObject
jsonObj.put("firstName", "John");
jsonObj.put("lastName", "Smith");
jsonObj.put("age", 25);
// for phone numbers, first create JSONArray
JSONArray jsonArr = new JSONArray();
// create LinkedHashMap
Map<String,String> map = new LinkedHashMap<String, String>();
map.put("type", "home");
map.put("number", "212 555-1234");
// adding map to list
jsonArr.put(map);
map.put("type", "fax");
map.put("number", "212 555-1234");
// adding map to list
jsonArr.put(map);
// putting phoneNumbers to JSONObject
jsonObj.put("phoneNumbers", jsonArr);
// Instantiate a new Gson instance.
Gson gson = new Gson();
// writing JSON to file:"JSONExample.json" in cwd
String json = gson.toJson(jsonObj);
这就是我得到的:
{
"map":
{
"firstName":"John",
"lastName":"Smith",
"age":25,
"phoneNumbers":
{
"myArrayList":
[
{
"map":
{
"type":"home",
"number":"212 555-1234"
}
},
{
"map":
{
"type":"fax",
"number":"212 555-1234"
}
}
]
}
}
}
如何摆脱 JSON 字符串中的“myArrayList”和“map”?
更新 我更改了代码的最后一部分:
// writing JSON to file:"JSONExample.json" in cwd
String json = jsonObj.toString();
它有效。但是当我像这样将“firstName”修改为“first”时:
// putting data to JSONObject
jsonObj.put("first", "John");
jsonObj.put("last", "Smith");
jsonObj.put("age", 25);
我得到了无序的字符串,这很奇怪。
{"last":"Smith","first":"John","age":25,"phoneNumbers":[{"type":"home","number":"212 555-1234"},{"type":"fax","number":"212 555-1234"}]}
我认为 GSON 库保持字符串有序。
解决方案
尝试使用优雅的json。这个库默认保存元素的顺序。这个 JSON:
{
"firstName": "John",
"lastName": "Smith",
"age": 25,
"phoneNumbers": [
{
"type": "home",
"number": "212 555-1234"
},
{
"type": "fax",
"number": "646 555-4567"
}
]
}
可以通过以下代码进行:
new JsonObject()
.add("firstName", new JsonString("John"))
.add("lastName", new JsonString("Smith"))
.add("age", new JsonInt(25))
.add(
"phoneNumbers",
new JsonArray()
.add(
new JsonObject()
.add("type", new JsonString("home"))
.add("number", new JsonString("212 555-1234"))
)
.add(
new JsonObject()
.add("type", new JsonString("home"))
.add("number", new JsonString("212 555-1234"))
)
).toJson();
注意:根据定义,JSON 没有排序。所以尽量不要依赖元素的顺序
推荐阅读
- python - 类来计算球体Python的面积
- postgresql - 从随机排序的列中按顺序提取数字
- python - 不知道如何解决错误:AttributeError: 'str' object has no attribute 'set'
- python - 如何使用列表/字典理解在 Python 中获取唯一值
- npm - Gulp sass 不编译带有 #{$i} 标签的循环
- javascript - 无法删除按钮上动态添加的类
- php - 如何上传文件并加密该文件并保存在数据库中
- python - 在 Python 中执行方法/函数时没有输出
- reactjs - 将泛型传递给封装在 HOC 中的组件
- node.js - 独占访问 mapLimit 中的变量返回