假设我的应用程序必须以此形式创建一个 JSON 文本文件
{
"key1"
:
"value1"
,
"key2"
:
"value2"
,
"arrayKey"
:
[
{
"keyA"
:
"valueA"
,
"keyB"
:
"valueB"
,
"keyC"
:
[
0
,
1
,
2
]
}
]
}
来自
JSONObject.toString()
这是我的 Android Java 应用程序中的一长行文本
{"key1":"value1","key2":"value2","arrayKey":[{"keyA":"valueA","keyB":"valueB","keyC":[0,1,2]}]}
事实证明,正则表达式方法不起作用。
有很多陷阱。
所以我决定创建自己的解析器来完成工作
编辑:注意!以下代码中有一个错误,导致转义引号被视为正常引号,请参阅我对此问题的回答(也有进一步改进)
public static String JSONTextToCRSeparatedJSONText(String JSONText)
{
String result="";
String symbolList="{}[]:,";
char ch;
char previousChar=0;
int charNum=JSONText.length();
boolean inRegion=false;
boolean insertedBefore=false;
char startRegionChar=0;
for (int i=0;i<charNum;i++)
{
ch=JSONText.charAt(i);
previousChar=ch; // mistake here, should be after the conditional statements, please see my answer with new code version
if (!inRegion)
{
if (((ch=='\"')||(ch=='\''))&&(previousChar!='\\'))
{
inRegion=true;
startRegionChar=ch;
}
} else
{
if ((ch==startRegionChar)&&(previousChar!='\\'))
{
inRegion=false;
}
}
if ((!inRegion)&& (symbolList.indexOf(ch)>-1)&&(!insertedBefore))
{
result=result+"\n";
}
result=result+ch;
insertedBefore=false;
if ((!inRegion)&& (symbolList.indexOf(ch)>-1))
{
result=result+"\n";
insertedBefore=true; //it will be useful next iteration
}
}
return result;
}
看起来很有效。
只是我想知道
如果它检查插入\n 控制字符的符号是否是 JSON 文本中可能存在的所有符号
以及是否存在一些我看不到的陷阱。
最佳答案
我认为你一个人做的工作太多了。目前有 2 个主要的已知库可用于处理 JSON。一个是 Jackson-JSON(也称为“Fast XML” - 想想看...),另一个是 GSON - 一个基于 Jackson-JSON 的 Google 库,但也支持传递二进制对象。我个人更喜欢 Jackson-JSON,但这是个人喜好的问题。对于 GSON 库,请查看 here 。 jackson 看看 here 。对于 Jackson 的 Maven 工件,请查看 here 。如果您选择与 Jackson 合作,那么您需要的主类是 ObjectMapper 。
从研究 readValue()
和 writeValue()
方法开始。在网络上寻找无数关于如何使用它的示例。这应该会给你一个好的开始。
无论如何,这两个库都允许您生成格式良好的 JSON。对于 Gson:
String content = new String(Files.readAllBytes(resource.toPath()));
Gson gson = new GsonBuilder().setPrettyPrinting().create();
JsonParser jp = new JsonParser();
JsonElement je = jp.parse(content);
String prettyJsonString = gson.toJson(je);
System.out.println(prettyJsonString);
return prettyJsonString;
对于 Jackson-JSON:
ObjectMapper mapper = new ObjectMapper();
mapper.enable(SerializationFeature.INDENT_OUTPUT);
String prettyJsonString = mapper.writeValueAsString(content);
return prettyJsonString;
与您所做的工作相比,您所做的工作要少得多,并且经过了更好的测试。另外,如果您想在 Html 中呈现相同的格式,请参阅此问题的答案:Pretty print for JSON in JAVA works fine for the console, but in browser it does not work
关于用于在符号处按行分割 JSON 文本的 Java 例程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58525215/