简体   繁体   中英

file content to JSON encoded String in Java

I want to read the content of a file, save it to a string and convert this string to a JSON encoded string.

For example I have a XML file with the following content (simplified):

<node name="myname">
    <id>123-abc</id>
</node>

It's only an example. The file type is not relevant, it can be a XML, a txt file or whatever. The main point is that I want to read a file content and convert this file content to a JSON encodes string.

Now I read this file with BufferedReader line for line and convert it to a String.

But this String is not JSON encoded. Now I've tried to convert it to a JSON String with JSONObject.quote(xmlString) . I thought that this was the solution, but it isn't so. After doing that the string looks like:

"<node name=\"myname\">\t<id>123-abc<\/id><\/node>"

After that I've tried replacing all \\t and the " at the beginning and the end of the string with an empty string, but this is not a smart solution. There have to be a standard solution I hope.

So, what can be a simple solution to convert a XML file content to an encoded JSON string?

With JAXB you can bind XML documents to POJOs. And then from a Java Object you can use eg Jackson

Try to Google mkyong.com. He has good basic tutorials for both JAXB and Jackson. Can't post more than 2 links as I dont have enough reputation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM