[英]Format a String in Json style
I extracted a huge String from a webpage and want to style/formatting this in Json style. 我从网页上提取了一个巨大的String,并希望以Json样式设置样式/格式。 The extracted String was originally a Json format but now after extracting this is just a long String.
提取的String最初是Json格式,但现在提取后只是一个很长的String。 I used JsonObj for this and the formatter does curios things, he moved text from the bottom to top changed the generally the line orders etc.
我为此使用了JsonObj,格式化程序完成了一些古玩的事情,他从下到上移动了文本,通常改变了行顺序等。
http://pastebin.com/exwwc6SY JsonFile after Formatting 格式化后http://pastebin.com/exwwc6SY JsonFile
http://pastebin.com/WHXtE36G The extracted String http://pastebin.com/WHXtE36G提取的字符串
And here the code 这是代码
try {
FileWriter fw = new FileWriter("/tmp/1.txt");
String line = ROUtils.getStringFromInputStream(urlConnection.getInputStream());
System.out.println(line);
String jsonObj = new JSONObject(line).toString(2);
fw.write(jsonObj);
} catch (IOException e) {
e.printStackTrace();
}
And the getStringFromInputStream() method 还有getStringFromInputStream()方法
public static String getStringFromInputStream(InputStream is) {
BufferedReader br = null;
StringBuilder sb = new StringBuilder();
String line;
try {
br = new BufferedReader(new InputStreamReader(is));
while ((line = br.readLine()) != null) {
sb.append(line);
}
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
if (br != null) {
try {
br.close();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
return sb.toString();
}
I found a new issue. 我发现了一个新问题。 The JsonObj File its not equal to the original String.
JsonObj文件不等于原始String。 I compared the number of Characters (no spaces).
我比较了字符数(无空格)。 The original String has 96311 and the JsonObj has 92636. Can anyone give me a hint what should I do?
原始String具有96311,而JsonObj具有92636。任何人都可以给我提示我该怎么办?
You cannot and should not rely on the ordering of elements within a JSON object. 您不能也不应该依赖JSON对象中元素的顺序。
From the JSON specification at http://www.json.org/ 来自http://www.json.org/的JSON规范
An object is an unordered set of name/value pairs. 对象是名称/值对的无序集合。
I found it out why i missed 4000 characters after converting. 我发现了为什么我在转换后错过了4000个字符。 I forgot to close the FileWriter!
我忘了关闭FileWriter!
fw.close();
The close() methods calls the flush() method so that the last buffered piece of the String can written down. close()方法调用flush()方法,以便可以记下String的最后一个缓冲区。
Thank u guys. 谢谢你们。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.