首页 > 解决方案 > 忽略 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>

我该如何处理?

标签: javajsonxmlxml-parsing

解决方案


我认为您需要在转换之前调整 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>

推荐阅读