[英]How can I convert the complete Json String into an XML in Java
First i hope the topic is not old, but i didn't find something.首先,我希望这个话题不老,但我没有找到任何东西。 So either you can write me a solution hint or where i find the topic.所以要么你可以给我写一个解决方案提示,要么我在哪里找到主题。 Thanks.谢谢。 And here is my problem i get a json response string back.这是我的问题,我得到一个 json 响应字符串。 The String looks like this:字符串看起来像这样:
{
"total": 3,
"hasMore": true,
"tasks": [
{
"taskId": "1",
"processName": "request new requests",
},
{
"taskId": "2",
"processName": "request new requests",
},
{
"taskId": "3",
"processName": "request new requests",
}
],
"totalSize": 6,
"nextIndex": 5,
"userTypeInTask": false
}
My goal is to convert this string to XML as follows:我的目标是将此字符串转换为 XML,如下所示:
<tasks>
<task>
<taskId>1</taskId>
<processName>request new requests</processName>
</task>
<task>
<taskId>2</taskId>
<processName>request new requests</processName>
</task>
<task>
<taskId>2</taskId>
<processName>request new requests</processName>
</task>
<totalSize>6</totalSize>
<total>3</total>
<hasMore>true</hasMore>
<nextIndex>5</nextIndex>
<userTypeInTask>false</userTypeInTask>
</tasks>
I managed to get the array but then I lose the other information.我设法得到了阵列,但后来我失去了其他信息。
import org.json.JSONArray;
import org.json.JSONObject;
public class jsontest {
@SuppressWarnings("null")
public static void main(String[] args) {
String jsonstring = "{\"total\": 3,\"hasMore\": true,\"tasks\":[{\"taskId\":\"1\",\"processName\": \"request new requests\"},{\"taskId\":\"2\",\"processName\": \"request new requests\"},{\"taskId\":\"2\",\"processName\": \"request new requests\"}],\"totalSize\": 6,\"nextIndex\": 5,\"userTypeInTask\": false}";
String parent = "tasks";
String child = "task";
JSONObject json = new JSONObject(jsonstring);
System.out.println("json: " + json);
if (json.has(parent)) {
JSONObject dataObject = json.optJSONObject(parent);
if (dataObject != null) {
System.out.println("dataObject 1: " + dataObject);
} else {
System.out.println("dataObject 2: " + dataObject);
JSONArray array = dataObject.getJSONArray(parent);
System.out.println("array: " + array);
String xml = "<" + parent + ">" + org.json.XML.toString(array, child) + "</" + parent + ">";
System.out.println("xml: " + xml);
}
}
}
}
Does anyone have a suggestion for my problem?有人对我的问题有建议吗?
Based on this solution https://stackoverflow.com/a/19978281/9474700 first import library in your gradle基于此解决方案https://stackoverflow.com/a/19978281/9474700首先在您的 gradle 中导入库
implementation 'org.json:json:20211205'实施 'org.json:json:20211205'
then do as below然后做如下
JSONObject json = new JSONObject(str);
String xml = XML.toString(json);
Second option第二个选项
Use from underscore-java从 underscore-java 使用
import library导入库
implementation 'com.github.javadev:underscore:1.74'
then然后
String xml = U.jsonToXml(jsonString);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.