2

I want convert json to xml here is code

public class ConvertJSONtoXML {

public static void main(String[] args) throws Exception {

    InputStream is = ConvertJSONtoXML.class.getResourceAsStream("demo1.txt");

        String jsonData = IOUtils.toString(is);
        XMLSerializer serializer = new XMLSerializer();
        JSON json = JSONSerializer.toJSON(jsonData);

    String xml = serializer.write((JSON) json);
        System.out.println(xml);

Here is demo1.txt

{"name":"naveed" }

It reads demo1.txt file and convert into xml but i m trying to pass json as string.

String jsonString="{\"name\":\"naveed\" }";
InputStream is = ConvertJSONtoXML.class.getResourceAsStream(jsonString);

but it wont work for string..

i thing getResourceAsStream(jsonString) doesnt work for string.... please suggest any reference

3
  • Looks like you'd have to parse an object first, and then serialize to xml. Or be the first to create cross serializer. Commented Sep 17, 2012 at 10:25
  • I think you use getResourceAsStream incorrectly. It is certainly impossible to pass to it JSON string: docs.oracle.com/javase/1.4.2/docs/api/java/lang/… Commented Sep 17, 2012 at 10:30
  • Underscore-java library has a static method U.jsonToXml(). Commented Jul 9, 2021 at 14:00

1 Answer 1

2

The method getResourceAsStream() actually looks on the file system for resource identified by the input string and open an input stream for it.

You should rather use something like

InputStream is = new ByteArrayInputStream( jsonString.getBytes() );

Also, you should take care of using compatible charsets.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.