my_doubt
my_doubt

Reputation: 63

How to remove elements from json, while parsing from xml using java

import org.json.JSONObject;
import org.json.XML;

public class Example {
        public static void main(String[] args) {
        String xmlString = "<users><user name=test1 age=20></user><type><direct num=3></direct></type><report sub=eng score=30></report></users>";
        JSONObject jsonObject = XML.toJSONObject(xmlString);
        System.out.println(jsonObject);
    }
}

I can remove elements after conversion from xml to json. But actually what i needed is that, the elements or attributes should be removed during conversion itself.

My required output is:

{
  "users": {
    "report": {
      "score": 30
    },
    "type": {
      "direct": {
        "num": 3
      }
    },
    "user": {
      "age": 20
    }
  }
}

Upvotes: 0

Views: 1206

Answers (2)

Vikas
Vikas

Reputation: 7185

XML class does not provide methods to exclude tags. One possible solution is update the string to remove tags as below,

e.g to exclude type tag,

String splits[] = xmlString.split("(<\\/type>|<type>)");
xmlString = splits[0]+splits[2];

JSONObject jsonObject = XML.toJSONObject(xmlString);
System.out.println(jsonObject);

Output:

{"users":{"report":{"sub":"eng","score":30},"user":{"name":"test1","age":20}}}

To remove name element from user tag,

String xmlString = "<users><user name=test1 age=20></user><type><direct num=3></direct></type><report sub=eng score=30></report></users>";

//split by user tags
String splits[] = xmlString.split("(<\\/user>|<user )");

//remove name filed and combine other elements
String user1 = Arrays.stream(splits[1].split(" "))
        .filter(s->!s.contains("name"))
        .collect(Collectors.joining(" "));

//merge strings and user tag
xmlString = splits[0] + "<user " + user1 + "</user>" + splits[2];

JSONObject jsonObject = XML.toJSONObject(xmlString);

Output::

{
    "users": {
        "report": {
            "sub": "eng",
            "score": 30
        },
        "type": {
            "direct": {
                "num": 3
            }
        },
        "user": {
            "age": 20
        }
    }
}

UPDATE: The best solution would be to remove from JsonObject,

jsonObject.getJSONObject("users").getJSONObject("user").remove("name")

Upvotes: 1

Arunavo
Arunavo

Reputation: 54

org.json.XML package doesn't provide internal XML modifications. If you must use this, you have to make the necessary modifications in the json by yourself. Else you can preprocess the xml using java default xml parser, convert it to string and then convert it to json.

Upvotes: 0

Related Questions