簡體   English   中英

使用 org.json 的 JSON 格式

[英]JSON Format using org.json

我正在使用 org.json 類將 XML 消息轉換為 JSON 並且轉換工作正常,但是轉換后的 JSON 消息具有根和行元素,如下面的屏幕截圖 1 所示,並且我們要求有一個沒有任何根和行的 JSON 消息,如圖所示屏幕截圖 2

我嘗試了不同的方式,但一直都沒有成功

XML 到 JSON 轉換的消息

XML 到 JSON 轉換的消息

要求是有沒有根和行的 JSON 消息,JSON 消息應該只有“公司詳細信息”

沒有節點的必需 JSON 消息

下面是我用來轉換為讀取傳入 XML 消息並將其成功轉換為 JSON 消息的 Java 代碼,現在嘗試僅讀取“CompanyDetails”並忽略根和行元素關於我做錯了什么的任何建議以實現所需的 JSON消息表示贊賞

import java.io.InputStream;
import java.io.OutputStream;
import org.json.JSONObject;
import org.json.XML;
import com.sap.aii.mapping.api.AbstractTransformation;
import com.sap.aii.mapping.api.StreamTransformationException;
import com.sap.aii.mapping.api.TransformationInput;
import com.sap.aii.mapping.api.TransformationOutput;

public class XML2JSON extends AbstractTransformation {
  @Override
  public void transform(TransformationInput transformationInput, TransformationOutput transformationOutput)
  throws StreamTransformationException {
  InputStream inputStream = transformationInput.getInputPayload().getInputStream();
  OutputStream outputStream = transformationOutput.getOutputPayload().getOutputStream();
  try {
  byte[] buf = new byte[inputStream.available()];
  inputStream.read(buf);
  JSONObject xmlJsonObj = XML.toJSONObject(new String(buf, "utf-8"));
  String jsonPrettyPrintString = xmlJsonObj.toString(4);
  byte[] bytes = jsonPrettyPrintString.toString().getBytes("UTF-8");
  outputStream.write(bytes);
    } catch (Exception e) {
  getTrace().addDebugMessage("Exception while writing OutputPayload: IOException", e);
  throw new StreamTransformationException(e.toString());
  }
  }
}

這條線之后

JSONObject xmlJsonObj = XML.toJSONObject(new String(buf, "utf-8"));

您需要繼續將對象解析為行

JSONArray xmlJsonArr = xmlJsonObj.getJSONArray("root")
    .getJSONObject(0)
    .getJSONArray("row");

然后將xmlJsonArr寫入文件

不清楚根中是否有多個對象,但如果是這樣,您將需要遍歷根數組的對象,然后構建您自己的所有內部行對象的 JSONArray

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM