Converting xml to json using jackson

前端 未结 3 765
执念已碎
执念已碎 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:48

    I also ran into this issue, using Jackson 2.5. My solution was to replace the implementation of javax.json.JsonObjectBuilder in use with my own, which when a new object is added behaves like this :

    public class CustomJsonObjectBuilder implements JsonObjectBuilder {
    
      private final Map jsonFragments;
    
      // other methods omitted for brevity
    
       public JsonObjectBuilder add(String name, JsonValue value) {
         if(jsonFragments.containsKey(name)) {
            JsonValue oldValue = jsonFragments.get(name);
            JsonArrayBuilder newBuilder = new JsonArrayBuilderImpl();
            if(oldValue instanceof JsonArray) {
                JsonArray theArray = (JsonArray) oldValue;
                for (JsonObject oldValues : theArray.getValuesAs(JsonObject.class)) {
                    newBuilder.add(oldValues);
                }
            } else {
                newBuilder.add(oldValue);
            }
            newBuilder.add(value);
            jsonFragments.put(name, newBuilder.build());
         } else {
            jsonFragments.put(name, value);
         }
         return this;
       }
    

提交回复
热议问题