java - 忽略 JSON 到 XML 转换中的键
问题描述
我正在使用 json 库将 json 转换为 xml,但是在转换时我想忽略要转换为 xml 标签的嵌套 json 对象。
例如。
平面 json 为:
{"id":"9568","name":"Customer Analysis","group":"demo","param":{"globalSettings":{"showLegends":false,"legendPosition":"bottom center"}}}
JSONObject json = new JSONObject("{\"id\":\"9568\",\"name\":\"Customer Analysis\",\"group\":\"demo\",\"param\":{\"globalSettings\":{\"showLegends\":false,\"legendPosition\":\"bottom center\"}}}");
String xml = XML.toString(json);
System.out.println(xml);
现在在上面的例子中,我想在里面有一个 json 的 xml。而现在在 globalSettings 中为 showLegends 和 legendPosition 创建了各种元素。
当前的 XML 如下:
<name>Customer Analysis</name>
<id>9568</id>
<group>demo</group>
<param>
<globalSettings>
<showLegends>false</showLegends>
<legendPosition>bottom center</legendPosition>
</globalSettings>
</param>
预期的 XML 应如下所示:
<name>Customer Analysis</name>
<id>9568</id>
<group>demo</group>
<param>
<globalSettings>
{"showLegends":false,"legendPosition":"bottom center"}
</globalSettings>
</param>
我该如何处理?
解决方案
我认为您需要在转换之前调整 JSON。你可以试试下面这个吗?
String json = "{\n" +
" \"user\": \"gerry\",\n" +
" \"likes\": [1, 2, 4],\n" +
" \"followers\": {\n" +
" \"options\": {\n" +
" \"key1\": \"a\",\n" +
" \"key2\": \"b\"\n" +
" } \n" +
" }\n" +
"}";
JSONObject jsonObject = new JSONObject(json);
JSONObject followers = jsonObject.getJSONObject("followers");
String options = followers.optString("options");
followers.put("options", options);
String s = XML.toString(jsonObject);
System.out.println(XML.unescape(s));
结果:
<followers><options>{"key1":"a","key2":"b"}</options></followers><user>gerry</user><likes>[1,2,4]</likes>
额外问题:
如果我不希望选项作为 xml 元素并且它应该是 json 的一部分怎么办?
String json = "{\n" +
" \"user\": \"gerry\",\n" +
" \"likes\": [1, 2, 4],\n" +
" \"followers\": {\n" +
" \"options\": {\n" +
" \"key1\": \"a\",\n" +
" \"key2\": \"b\"\n" +
" } \n" +
" }\n" +
"}";
JSONObject jsonObject = new JSONObject(json);
jsonObject.put("followers", jsonObject.optString("followers"));
// org.json 20180813
String s = XML.toString(jsonObject);
System.out.println(XML.unescape(s));
结果:
<followers>{"options":{"key1":"a","key2":"b"}}</followers><user>gerry</user><likes>1</likes><likes>2</likes><likes>4</likes>
推荐阅读
- java - Java Program. Need to simplified public boolean equals (object B){ is to long. I do not how to reduce the coding in that part of my program
- python - Python - 旧输入仍在输入缓冲区中?
- javascript - 将工作表添加到 Jquery 数据表的 excel 输出中
- r - 仅使用 2 个向量的部分分量的操作
- java - 为什么没有文件被退回?
- scala - scala中的伴侣对象
- c# - 您如何使用 ProtectedBrowserStorage 和 BlazorServer AspNet 身份验证进行基于 Cookie 的登录?
- android-studio - 不支持此模型:输入张量 0 没有名称
- javascript - 单击按钮时尝试更改游戏动作但不起作用
- python - Matplotlib 在重新绘制数据时清除旧的轴标签