【问题标题】:org.json unable to convert json to xml properly- json object with nested objects and arrays.Need alternate approachorg.json 无法正确地将 json 转换为 xml-带有嵌套对象和数组的 json 对象。需要替代方法
【发布时间】:2017-05-29 11:54:13
【问题描述】:

我需要将 json 转换为 xml。

我正在使用 org.json jar 文件

但是,xml 中元素的顺序不同,并且在转换时也缺少一些元素。输入消息是一个带有 json 数组的嵌套 json 对象。 对于简单的 json 到 xml,代码可以正常工作。 请为此问题提供替代方法/库

package jjson;
import java.io.*;
import org.json.JSONObject;
import org.json.XML;
public class Json {

public static void main (String args[]) {
    InputStreamReader is = null;
    BufferedReader br = null;
    StringBuilder sb = null;

    try {

        File jsonFile = new File("<<provide location of file>>");
        is = new InputStreamReader(new FileInputStream(jsonFile), "UTF-8");

        // Read the input stream and covert into string object
        //is = new InputStreamReader(inputStream);
        sb = new StringBuilder();
        br = new BufferedReader(is);
        String read = br.readLine();

        while (read != null) {
            // System.out.println(read);
            sb.append(read);
            read = br.readLine();

        }

        // Convert the String object to XML and write in the default name

        String xml = XML.toString(new JSONObject(sb.toString()));
        System.out.println(xml);
        //String service.write(xml.getBytes(), "default");
    } catch (Exception e) {
        // TODO Auto-generated catch block

    } finally {

        if (br != null) {
            try {
                br.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        if (is != null) {
            try {
                is.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
}
}

编辑:

输入消息

{
"Id": 1,
"Recipient": "xyz.ang@abcd.com",
"RequestedComments": null,
"GeneratedAutomatically": false,
"From": "Africa",
"To": "China",
"ResponsesPage": {
"Tables": [
  {
    "Name": null,
    "Columns": [
      "Question",
      "Response"
    ],
    "Rows": [
      {
        "Name": "1. General",
        "Columns": [
          {
            "Key": "Question",
            "Value": "1. General",
            "Name": "SECTION_GENERAL",
            "Type": null
          },
          {
            "Key": "Response",
            "Value": null,
            "Name": null,
            "Type": 5
          }
        ],
        "Status": 0,
        "ValidationMessage": null
      },
      {
        "Name": "1.1 Name of completing party",
        "Columns": [
          {
            "Key": "Question",
            "Value": "1.1 Name of completing party",
            "Name": "COMPLETING_PARTY",
            "Type": null
          },
          {
            "Key": "Response",
            "Value": "Captain",
            "Name": null,
            "Type": 0
          }
        ],
        "Status": 0,
        "ValidationMessage": null
      },
      {
        "Name": "1.2 Relationship",
        "Columns": [
          {
            "Key": "Question",
            "Value": "1.2 Relationship",
            "Name": "RELATIONSHIP",
            "Type": null
          },
          {
            "Key": "Response",
            "Value": "Owner",
            "Name": null,
            "Type": 1
          }
        ],
        "Status": 0,
        "ValidationMessage": null
      },
      {
        "Name": "2. Details",
        "Columns": [
          {
            "Key": "Question",
            "Value": "2. Details",
            "Name": "SECTION_DETAILS",
            "Type": null
          },
          {
            "Key": "Response",
            "Value": null,
            "Name": null,
            "Type": 5
          }
        ],
        "Status": 0,
        "ValidationMessage": null
      },
      {
        "Name": "2.1 FlatNumber",
        "Columns": [
          {
            "Key": "Question",
            "Value": "2.1 IMO Number",
            "Name": "IMP_NUMBER",
            "Type": null
          },
          {
            "Key": "Response",
            "Value": "9336012",
            "Name": null,
            "Type": 2
          }
        ],
        "Status": 0,
        "ValidationMessage": null
      }
    ]
   },
   {
    "Name": "IDENTIFIER_GRID",
    "Columns": [
      "Question",
      "Data",
      "Correction if required"
    ],
    "Rows": [
      {
        "Name": "2.2 Name",
        "Columns": [
          {
            "Key": "Question",
            "Value": "2.2 Name",
            "Name": "TEXT_QUESTION",
            "Type": null
          },
          {
            "Key": "Data",
            "Value": "IVS CABERNET",
            "Name": null,
            "Type": 0
          },
          {
            "Key": "2.2 Name",
            "Value": "",
            "Name": null,
            "Type": null
          }
        ],
        "Status": 0,
        "ValidationMessage": null
      },
      {
        "Name": "2.3",
        "Columns": [
          {
            "Key": "Question",
            "Value": "2.3",
            "Name": "TEXT_QUESTION",
            "Type": null
          },
          {
            "Key": "Data",
            "Value": "565598000",
            "Name": null,
            "Type": 0
          },
          {
            "Key": "2.3 Maritime Mobile",
            "Value": "",
            "Name": null,
            "Type": null
          }
        ],
        "Status": 0,
        "ValidationMessage": null
      },
      {
        "Name": "2.4 Build Date",
        "Columns": [
          {
            "Key": "Question",
            "Value": "2.4 Build Date",
            "Name": "TEXT_QUESTION",
            "Type": null
          },
          {
            "Key": "RightShip Data",
            "Value": "01 Oct 2007",
            "Name": null,
            "Type": 0
          },
          {
            "Key": "2.4 Build Date",
            "Value": "04 Oct. 2007",
            "Name": null,
            "Type": null
          }
        ],
        "Status": 0,
        "ValidationMessage": null
      }
    ]
  },
  {
    "Name": null,
     "Columns": [
      "Question",
      "Response"
     ],
     "Rows": [
      {
        "Name": "2.5 Vessel Type ",
        "Columns": [
          {
            "Key": "Question",
            "Value": "2.5 Vessel Type ",
            "Name": "SHIP_TYPE",
            "Type": null
          },
          {
            "Key": "Response",
            "Value": "Bulk Carrier",
            "Name": null,
            "Type": 1
          }
        ],
        "Status": 0,
        "ValidationMessage": null
      }
     ]
   },
   {
    "Name": "VESSEL_DETAILS_GRID",
    "Columns": [
      "Question",
      "Data",
      "Correction if required"
     ],
       "Rows": [
      {
        "Name": "10. Attachments",
        "Columns": [
          {
            "Key": "Question",
            "Value": "10. Attachments",
            "Name": "SECTION_ATTACHMENTS",
            "Type": null
          },
          {
            "Key": "Response",
            "Value": null,
            "Name": null,
            "Type": 5
          }
        ],
        "Status": 0,
        "ValidationMessage": null
      }
    ]
  }
]
},
"QuestionsCount": 147,
"RulesCount": 5,
"PassedCount": 5,
"RequiredCount": 0,
"FCount": 0,
"VId": 190980,
"AId": null,
"AssignedTo": null,
"AssignedToName": null,
"AssignedToCustomer": null,
"AssignedOn": null,
"DecidedBy": "ABC",
"DecidedByName": "Red",
"DecidedByCustomerCode": "CSMC",
"DecidedByCustomerName": "CSG",
"DecidedOn": "2017-05-02T15:14:18.893Z",
"DecidedComments": "Acceptable",
"DecidedAutomatically": false,
"Vessel": {
 "Id": 190980,
 "IMP": 1234,
 "PrId": "12345",
 "Name": "IVS CABERNET",
 "Ttatus": "In Service/Commission",
 "VesselType": "Bulk Carrier",
 "DWT": 177173,
 "Age": 9.5,
 "ActivityConfigList": null,
 "Links": []
 },
 "Attachments": [],
 "History": null,
 "Comments": null,
 "Reports": [],
 "Links": []
 }

预期的输出 XML:(对于添加 JSON 作为根元素的示例)

<JSON>
<Id>1</Id>
<Recipient>xyz.ang@abcd.com</Recipient>
<RequestedComments/>
<GeneratedAutomatically>false</GeneratedAutomatically>
<From>Africa</From>
<To>China</To>
<ResponsesPage>
    <Tables>
        <Name/>
        <Columns>Question</Columns>
        <Columns>Response</Columns>
        <Rows>
            <Name>1. General</Name>
            <Columns>
                <Key>Question</Key>
                <Value>1. General</Value>
                <Name>SECTION_GENERAL</Name>
                <Type/>
            </Columns>
            <Columns>
                <Key>Response</Key>
                <Value/>
                <Name/>
                <Type>5</Type>
            </Columns>
            <Status>0</Status>
            <ValidationMessage/>
        </Rows>
        <Rows>
            <Name>1.1 Name of completing party</Name>
            <Columns>
                <Key>Question</Key>
                <Value>1.1 Name of completing party</Value>
                <Name>COMPLETING_PARTY</Name>
                <Type/>
            </Columns>
            <Columns>
                <Key>Response</Key>
                <Value>Captain</Value>
                <Name/>
                <Type>0</Type>
            </Columns>
            <Status>0</Status>
            <ValidationMessage/>
        </Rows>
        <Rows>
            <Name>1.2 Relationship</Name>
            <Columns>
                <Key>Question</Key>
                <Value>1.2 Relationship</Value>
                <Name>RELATIONSHIP</Name>
                <Type/>
            </Columns>
            <Columns>
                <Key>Response</Key>
                <Value>Owner</Value>
                <Name/>
                <Type>1</Type>
            </Columns>
            <Status>0</Status>
            <ValidationMessage/>
        </Rows>
        <Rows>
            <Name>2. Details</Name>
            <Columns>
                <Key>Question</Key>
                <Value>2. Details</Value>
                <Name>SECTION_DETAILS</Name>
                <Type/>
            </Columns>
            <Columns>
                <Key>Response</Key>
                <Value/>
                <Name/>
                <Type>5</Type>
            </Columns>
            <Status>0</Status>
            <ValidationMessage/>
        </Rows>
        <Rows>
            <Name>2.1 FlatNumber</Name>
            <Columns>
                <Key>Question</Key>
                <Value>2.1 IMO Number</Value>
                <Name>IMP_NUMBER</Name>
                <Type/>
            </Columns>
            <Columns>
                <Key>Response</Key>
                <Value>9336012</Value>
                <Name/>
                <Type>2</Type>
            </Columns>
            <Status>0</Status>
            <ValidationMessage/>
        </Rows>
    </Tables>
    <Tables>
        <Name>IDENTIFIER_GRID</Name>
        <Columns>Question</Columns>
        <Columns>Data</Columns>
        <Columns>Correction if required</Columns>
        <Rows>
            <Name>2.2 Name</Name>
            <Columns>
                <Key>Question</Key>
                <Value>2.2 Name</Value>
                <Name>TEXT_QUESTION</Name>
                <Type/>
            </Columns>
            <Columns>
                <Key>Data</Key>
                <Value>IVS CABERNET</Value>
                <Name/>
                <Type>0</Type>
            </Columns>
            <Columns>
                <Key>2.2 Name</Key>
                <Value/>
                <Name/>
                <Type/>
            </Columns>
            <Status>0</Status>
            <ValidationMessage/>
        </Rows>
        <Rows>
            <Name>2.3</Name>
            <Columns>
                <Key>Question</Key>
                <Value>2.3</Value>
                <Name>TEXT_QUESTION</Name>
                <Type/>
            </Columns>
            <Columns>
                <Key>Data</Key>
                <Value>565598000</Value>
                <Name/>
                <Type>0</Type>
            </Columns>
            <Columns>
                <Key>2.3 Maritime Mobile</Key>
                <Value/>
                <Name/>
                <Type/>
            </Columns>
            <Status>0</Status>
            <ValidationMessage/>
        </Rows>
        <Rows>
            <Name>2.4 Build Date</Name>
            <Columns>
                <Key>Question</Key>
                <Value>2.4 Build Date</Value>
                <Name>TEXT_QUESTION</Name>
                <Type/>
            </Columns>
            <Columns>
                <Key>RightShip Data</Key>
                <Value>01 Oct 2007</Value>
                <Name/>
                <Type>0</Type>
            </Columns>
            <Columns>
                <Key>2.4 Build Date</Key>
                <Value>04 Oct. 2007</Value>
                <Name/>
                <Type/>
            </Columns>
            <Status>0</Status>
            <ValidationMessage/>
        </Rows>
    </Tables>
    <Tables>
        <Name/>
        <Columns>Question</Columns>
        <Columns>Response</Columns>
        <Rows>
            <Name>2.5 Vessel Type </Name>
            <Columns>
                <Key>Question</Key>
                <Value>2.5 Vessel Type </Value>
                <Name>SHIP_TYPE</Name>
                <Type/>
            </Columns>
            <Columns>
                <Key>Response</Key>
                <Value>Bulk Carrier</Value>
                <Name/>
                <Type>1</Type>
            </Columns>
            <Status>0</Status>
            <ValidationMessage/>
        </Rows>
    </Tables>
    <Tables>
        <Name>VESSEL_DETAILS_GRID</Name>
        <Columns>Question</Columns>
        <Columns>RightShip Data</Columns>
        <Columns>Correction if required</Columns>
        <Rows>
           <Name>10. Attachments</Name>
           <Columns>
            <Key>Question</Key>
            <Value>10. Attachments</Value>
            <Name>SECTION_ATTACHMENTS</Name>
            <Type/>
          </Columns>
          <Columns>
          <Key>Response</Key>
           <Value/>
           <Name/>
           <Type>5</Type>
           </Columns>
           <Status>0</Status>
          <ValidationMessage/>
        </Rows>
    </Tables>
 </ResponsesPage>
 <QuestionsCount>147</QuestionsCount>
 <RulesCount>5</RulesCount>
 <PassedCount>5</PassedCount>
 <RequiredCount>0</RequiredCount>
 <FCount>0</FCount>
 <VId>190980</VId>
 <AId/>
 <AssignedTo/>
 <AssignedToName/>
 <AssignedToCustomer/>
 <AssignedOn/>
 <DecidedBy>ABC</DecidedBy>
 <DecidedByName>Red</DecidedByName>
 <DecidedByCustomerCode>CSMC</DecidedByCustomerCode>
 <DecidedByCustomerName>CSG</DecidedByCustomerName>
 <DecidedOn>2017-05-02T15:14:18.893Z</DecidedOn>
 <DecidedComments>Acceptable</DecidedComments>
 <DecidedAutomatically>false</DecidedAutomatically>
  <Vessel>
    <Id>190980</Id>
    <IMP>1234</IMP>
    <PrId>12345</PrId>
    <Name>IVS CABERNET</Name>
    <Ttatus>In Service/Commission</Ttatus>
    <VesselType>Bulk Carrier</VesselType>
    <DWT>177173</DWT>
    <Age>9.5</Age>
    <ActivityConfigList/>
    <Links/>
 </Vessel>
 <Attachments/>
 <History/>
 <Comments/>
 <Reports/>
 <Links/>
 </JSON>

谢谢, 克里什

【问题讨论】:

  • 请告诉我们输入 JSON 的样子、您希望目标 XML 的样子以及您当前的方法生成的内容。告诉我们“这行不通,您能提出其他建议吗”并不能充分说明您的要求。
  • 嗨,我已经添加了目标xml,并输入了json。它们最初很大,因此我没有将它们添加到帖子中。我现在通过编辑消息的内容添加了它们。我当前的输出缺少一些标签,并且有些标签的顺序不正确。
  • 在 JSON“对象”中,条目的顺序通常不被认为是重要的(在许多语言中,它会显示为映射、散列或字典,本质上是无序的)。因此,保留订单的要求可能很难满足。

标签: java json xml org.json


【解决方案1】:

以下 XSLT 3.0 样式表提供了您正在寻找的输出(它使用 json-to-xml() 函数将通用转换为 XML,然后将通用 XML 转换为您需要的特定形式):

<xsl:stylesheet 
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform" 
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    xmlns:fn="http://www.w3.org/2005/xpath-functions"
    expand-text="yes"
    exclude-result-prefixes="#all"
    version="3.0">

    <xsl:output method="xml" indent="yes"/>

    <xsl:template name="xsl:initial-template">
        <JSON>
            <xsl:apply-templates select="json-to-xml(unparsed-text('test.json'))"/>
        </JSON>
    </xsl:template>

    <xsl:template match="*[@key[. castable as xs:NCName]]" priority="2">
        <xsl:element name="{@key}">
            <xsl:apply-templates/>
        </xsl:element>       
    </xsl:template>

    <xsl:template match="*[@key[not(. castable as xs:NCName)]]" priority="2">
        <xsl:message terminate="yes">Key {@key} cannot be used as an element name</xsl:message>    
    </xsl:template>

    <xsl:template match="fn:array[@key[. castable as xs:NCName]][exists(*)]" priority="3">
        <xsl:for-each select="*">
            <xsl:element name="{../@key}">
                <xsl:apply-templates select="."/>
            </xsl:element>
        </xsl:for-each>
    </xsl:template>

    <xsl:template match="fn:array[@key[. castable as xs:NCName]][empty(*)]" priority="3">
        <xsl:element name="{@key}"/>
    </xsl:template>

</xsl:stylesheet>

【讨论】:

  • 谢谢迈克尔,我正在寻找一种关于如何将 json 转换为 xml 的方法。 org.json 逐行读取文件并将其转换为 jsonobject,然后将 jsonobject 转换为 xml 字符串。
  • 我将围绕该问题添加更多上下文。 1.在我的情况下,json 响应来自第三方。 2.Org.json - 我使用的代码,逐行读取文件并将其转换为 jsonobject,然后将 jsonobject 转换为 xml 字符串。 3. 另一方面,我给出的示例输出来自一个有可能将 json 转换为 xml 的工具。 4.所以,这个 xslt 是基于 xml 输出的权利,如果我的 json 响应发生变化,xslt 是否仍然适用,或者我会面临任何变化。谢谢大家。
  • XSLT 实现了我从您的示例中推断出的规则。如果您的 JSON 发生更改,例如,如果它使用无效的键值作为 XML 元素名称,则样式表将需要更改。没有将 JSON 转换为满足所有要求的 XML 的通用方法:这就是 XSLT 方法有用的原因,因为它使您可以灵活地自己定义规则。
  • 嗨迈克尔,我正在尝试在 java 中实现这个,在互联网上查找,因为我从未从事过类似的工作。我们需要任何支持的罐子吗?另外,这里可以使用 SAXON-B XSLT 2.0 吗?另外,在 json 到 xml 的转换过程中,数据或元素是否会丢失,就像 org.json 到字符串的转换一样?
  • Saxon 目前仅在商业版中实现 XSLT 3.0 - 您可以使用 Saxon-PE 9.7 运行它(获得 30 天评估许可证)。当 3.0 成为推荐时,对 XSLT 3.0 的支持将进入开源 Saxon-HE 产品,希望很快。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-04-03
  • 1970-01-01
  • 2017-06-08
  • 2023-02-15
  • 2016-09-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多