datafile4
datafile4

Reputation: 69

How to keep spaces in tags when converting xml to json in Java?

I have the following xml:

<root><field>test  </field></root>

When I try to convert it to json,

    String xmlString = "<root><field>test  </field></root>";
    String jsonString = XML.toJSONObject(xmlString, false).toString();
    System.out.println(jsonString);

the result is like this:

{"root":{"field":"test"}}

How can I keep spaces in strings when converting?

Upvotes: 0

Views: 1523

Answers (1)

Valentyn Kolesnikov
Valentyn Kolesnikov

Reputation: 2097

Underscore-java library can keep spaces while conversion from XML to JSON. I am the maintainer of the project.

import com.github.underscore.U;

public class MyClass {
    public static void main(String args[]) {
        System.out.println(U.xmlToJson("<root><field>test  </field></root>"));
   }
}

Output:

{
  "root": {
    "field": "test  "
  },
  "#omit-xml-declaration": "yes"
}

Upvotes: 1

Related Questions