在java中将字符串转换为json格式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21349568/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 08:13:00  来源:igfitidea点击:

convert a string to json format in java

javajsonmongodb

提问by PathuZ

I want to extract data from different blogs. I have done it using article extractor but now I have to convert it into json format for storing into MongoDB. My program is returning entire article as string like this:

我想从不同的博客中提取数据。我已经使用文章提取器完成了它,但现在我必须将其转换为 json 格式以存储到 MongoDB 中。我的程序将整篇文章作为这样的字符串返回:

String news=ArticleExtractor.INSTANCE.getText(doc);

How can I convert it into json format?

如何将其转换为json格式?

     URL url;
       url = new URL("http://blogs.timesofindia.indiatimes.com/mellowdrama/entry/india-needs-a-law-against-community-crime");
InputSource is = HTMLFetcher.fetch(url).toInputSource();        
       BoilerpipeSAXInput in = new BoilerpipeSAXInput(is);
     TextDocument doc = in.getTextDocument();        
     news=ArticleExtractor.INSTANCE.getText(doc);
     System.out.println(news);
     JSONObject jsonObj = new JSONObject(news);

this last line shows error... the error is

最后一行显示错误...错误是

    Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
The constructor JSONObject(String) is undefined

at Article_ext.main(Article_ext.java:39)

采纳答案by Joop Eggen

JSONObject jsonObj = new JSONObject();
jsonObj.append("news", news);

回答by poitroae

If you want to parse the JSON you can use the JSONObject.

如果要解析 JSON,可以使用JSONObject.

回答by Kamlesh Arya

You can try JSONObjectfor conversion of String to Json Format

您可以尝试JSONObject将字符串转换为 Json 格式

Try this way:

试试这个方法:

JSONObject jsonObj = new JSONObject("Your String");

Use org.json

使用org.json