Create xml data transformation by DOM parsing of json data format

Keywords: Programming JSON xml encoding

Create xml data transformation by DOM parsing of json data format

The first JSON tool to use is org.json

In the past, FastJson was used. At the beginning of contact, it was still around many pits. However, it was also very easy to touch some of them at last
Start with the code dome
{"result":
[{"comments":
[{"id":"489ac5ea-c13b-4c6f-8723-25b1956acf32",
"content": "this is a good article",
"who":{"nickname":"pc","id":"76983229-93c4-45ee-9176-f90497468af2"}},
{"id":"a827f6a6-44dd-4f25-84bd-1181d415c025",
"content": "when will Jiahui start to lose weight",
"who":{"nickname":"pc","id":"76983229-93c4-45ee-9176-f90497468af2"}}],
"emotions":0,"postedAt":"2014-02-11T00:00:00+08:00",
"author":{"nickname":"redan",
"id":"d23fa0a6-be5d-401b-9763-10440fb15bcc"},
"id":"7c926954-f637-4dda-82c5-442f868dc006",
"Content": "this is content this is an article"}],
"status":200}

The first time that the data returned by json is not fixed
@RequestMapping(value = "/viewIterator")
public void viewIterator(HttpServletRequest request,
HttpServletResponse response) throws IOException, ParserConfigurationException, TransformerException {

            //Create parsing DOM parser
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document doc = builder.newDocument();
            //Root element
            Element documentElement = doc.createElement("document");
            doc.appendChild(documentElement);
            //Response data
            CloseableHttpResponse response1 = HttpClients.createDefault().execute(new HttpGet("https://redan-api.herokuapp.com/story/"));
            //Return to get entity
            HttpEntity entity = response1.getEntity();
            if (entity != null) {

                    String str = EntityUtils.toString(entity, "UTF-8");
                    //Turn this string into a json array
                    JSONArray jsonArray = new JSONObject(str).getJSONArray("result");
                    //Get the first one
                    JSONObject jsonObject = jsonArray.getJSONObject(0);
                    //Get all the values through the first object
                    Iterator<String> keys = jsonObject.keys();
                    //
                    while (keys.hasNext()) {
                            //All key s on the first level
                            String next = keys.next();

                            //Get the value of the key corresponding to the object
                            String getKey = jsonObject.get(next).toString();
                            System.out.println("For the first time key-- " + next + "For the first time values" + getKey);
                            //  doc.createElement(getKey);
                            //In the case of text
                            Element element1 = doc.createElement(next);
                            if (!(getKey.endsWith("}") || getKey.endsWith("]"))) {
                                    //Create child nodes of the first layer

                                    System.out.println(next + "     " + getKey);
                                    element1.setTextContent(getKey);
                            }

                            documentElement.appendChild(element1);
                            if (getKey.endsWith("}")) {
                                    //Layer 2 json objects
                                    JSONObject jsonObject2 = jsonObject.getJSONObject(next);
                                    //key of json object
                                    Iterator<String> key1 = jsonObject2.keys();
                                    while (key1.hasNext()) {
                                            //Get all the key s
                                            String next1 = key1.next();
                                            String value2 = jsonObject2.getString(next1);

                                            Element element2 = doc.createElement(next1);

                                            element2.setTextContent(value2);
                                            element1.appendChild(element2);

                                    }

                            } //If json is an array
                            if (getKey.endsWith("]")) {

                                    JSONArray jsonArray1 = jsonObject.getJSONArray(next);
                                    for (int i = 0; i < jsonArray1.length(); i++) {
                                            JSONObject jsonObject2 = jsonArray1.getJSONObject(i);
                                            Iterator<String> key3 = jsonObject2.keys();
                                            while (key3.hasNext()) {
                                                    //Get all the key s
                                                    String next2 = key3.next();

                                                    String value3 = jsonObject2.get(next2).toString();

                                                    Element element3 = doc.createElement(next2);
                                                    if (!value3.endsWith("}")) {
                                                            element3.setTextContent(value3);

                                                    }
                                                    element1.appendChild(element3);
                                                    //Judge whether the third layer is still a json pair
                                                    if (value3.endsWith("}")) {
                                                            JSONObject jsonObject3 = jsonObject2.getJSONObject(next2);

                                                            Iterator<String> key4 = jsonObject3.keys();
                                                            while (key4.hasNext()) {
                                                                    String next5 = key4.next();
                                                                    //Get the corresponding valus through key
                                                                    String value = jsonObject3.getString(next5);
                                                                    System.out.println(next5 + "   Value of the third layer " + value);
                                                                    Element element4 = doc.createElement(next5);
                                                                    element4.setTextContent(value);

                                                                    element3.appendChild(element4);
                                                            }

                                                    }

                                            }
                                    }
                            }

                    }
            }

            //Update to this project
            TransformerFactory.newInstance().newTransformer().transform(new DOMSource(doc), new StreamResult(response.getOutputStream()));

    }

< ----------------------------------------------------- gorgeous split line
The improved code is as follows
Access the above json data returned. The code in the controller is as follows

    @RequestMapping(value = "/getView")
    @ResponseBody
    public void getView(HttpServletRequest request,
            HttpServletResponse response) throws IOException, ParserConfigurationException, TransformerException {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document doc = builder.newDocument();

            //Root element created
            Element documentElement = doc.createElement("document");
            doc.appendChild(documentElement);
            //Create client

            CloseableHttpResponse response1 = HttpClients.createDefault().execute(new HttpGet("https://redan-api.herokuapp.com/story/"));
            //Return string entity

            HttpEntity entity1 = response1.getEntity();
            if (entity1 != null) {
                    //Set the code for the returned entity
                    String retSrc = EntityUtils.toString(entity1, "UTF-8");
                    //It's an array that gets the outermost element
                    JSONArray storyList = new JSONObject(retSrc).getJSONArray("result");

                    // Then, go through the elements and take out all the elements
                    for (int i = 0; i < storyList.length(); i++) {
                            //Get each array element of json, judge whether the element of json array is an object or an array
                            JSONObject jsonObject = storyList.getJSONObject(i);

                            Iterator<String> next1 = jsonObject.keys();

                            while (next1.hasNext()) {
                                    String next2 = next1.next();
                                    //In the case of text
                                    Element documentNext2 = doc.createElement(next2);
                                    String teString = jsonObject.get(next2).toString();
                                    if (!(next2.equals("author") || next2.equals("comments"))) {

                                            documentNext2.setTextContent(teString);

                                    }
                                    documentElement.appendChild(documentNext2);
                                    //In the comments array
                                    if (next2.equals("comments")) {
                                            JSONArray jsonArray = jsonObject.getJSONArray(next2);
                                            //Create label node

                                            for (int j = 0; j < jsonArray.length(); j++) {
                                                    JSONObject jsonObject3 = jsonArray.getJSONObject(j);
                                                    Iterator<String> next3 = jsonObject3.keys();
                                                    while (next3.hasNext()) {
                                                            String next4 = next3.next();
                                                            Element elementNext4 = doc.createElement(next4);
                                                            if (!next4.equals("who")) {
                                                                    String vaString = jsonObject3.getString(next4);
                                                                    elementNext4.setTextContent(vaString);

                                                            }
                                                            //Convert the json key to the corresponding xml tag
                                                            if (next4.equals("who")) {
                                                                    JSONObject jsonObject4 = jsonObject3.getJSONObject(next4);
                                                                    Iterator<String> next5 = jsonObject4.keys();
                                                                    while (next5.hasNext()) {
                                                                            String next6 = next5.next();
                                                                            String vaString = jsonObject4.getString(next6);
                                                                            Element documentNext6 = doc.createElement(next6);
                                                                            documentNext6.setTextContent(vaString);

                                                                            elementNext4.appendChild(documentNext6);
                                                                    }
                                                            }
                                                            documentNext2.appendChild(elementNext4);

                                                    }

                                            }

                                    }
                                    if (next2.equals("author")) {
                                            JSONObject jsonObject5 = jsonObject.getJSONObject(next2);
                                            Iterator<String> next7 = jsonObject5.keys();
                                            while (next7.hasNext()) {
                                                    String next8 = next7.next();
                                                    String vaString2 = jsonObject5.getString(next8);
                                                    //Create node label
                                                    Element documentNext8 = doc.createElement(next8);
                                                    documentNext8.setTextContent(vaString2);

                                                    documentNext2.appendChild(documentNext8);
                                            }

                                    }

                            }

                    }

            }
            //Update to this project
            TransformerFactory.newInstance().newTransformer().transform(new DOMSource(doc), new StreamResult(response.getOutputStream()));

    }

#Converted xml

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<comments>
    <id>c4087de9-895d-4171-934a-eff811b05e9e</id>
    <content>This is a good article</content>
    <who>
        <nickname>pc</nickname>
        <id>02c83d70-7720-488b-9e74-43492eeb4a23</id>
    </who>
    <id>67dac6e9-44dd-4ecc-be85-15673cee95dd</id>
    <content>When will Hui start to lose weight</content>
    <who>
        <nickname>pc</nickname>
        <id>02c83d70-7720-488b-9e74-43492eeb4a23</id>
    </who>
</comments>
<emotions>0</emotions>
<postedAt>2014-02-11T00:00:00+08:00</postedAt>
<author>
    <nickname>redan</nickname>
    <id>82c8a212-1523-4582-9639-6f2abb8f35bb</id>
</author>
<id>8d89d872-d97d-4e16-b65b-fe21c9bdf74b</id>
<content>this is content This is an article</content>

So in contrast, it's written according to the fixed data format of the returned json. It's also more intuitive. Don't be as complex as the judgment of the first dom
The above is my personal code inadequacy also hope you to teach

Posted by numan82 on Wed, 04 Dec 2019 16:36:00 -0800