Converting xml to json using jackson

前端 未结 3 796
执念已碎
执念已碎 2021-01-07 04:25

I want to convert an xml to json.

The format of of xml is as follows -

  
                            
        

        
3条回答
  •  滥情空心
    2021-01-07 04:46

    I was able to get the solution to this problem by using org.json API to convert source XML to JSONObject and then to JSON by Jackson API.

    Code

    import java.io.File;
    import java.io.FileInputStream;
    import java.io.InputStream;
    
    import org.apache.commons.io.IOUtils;
    import org.json.JSONObject;
    import org.json.XML;
    
    import com.fasterxml.jackson.databind.ObjectMapper;
    import com.fasterxml.jackson.databind.SerializationFeature;
    
    ...
    ...
    
    try (InputStream inputStream = new FileInputStream(new File(
                    "source.xml"))) {
        String xml = IOUtils.toString(inputStream);
        JSONObject jObject = XML.toJSONObject(xml);
        ObjectMapper mapper = new ObjectMapper();
        mapper.enable(SerializationFeature.INDENT_OUTPUT);
        Object json = mapper.readValue(jObject.toString(), Object.class);
        String output = mapper.writeValueAsString(json);
        System.out.println(output);
    }
    
    ...
    ...
    

提交回复
热议问题