Let's say my app has to create a JSON text file in this form
{
"key1"
:
"value1"
,
"key2"
:
"value2"
,
"arrayKey"
:
[
{
"keyA"
:
"valueA"
,
"keyB"
:
"valueB"
,
"keyC"
:
[
0
,
1
,
2
]
}
]
}
from
JSONObject.toString()
that is one long line of text in my Android Java app
{"key1":"value1","key2":"value2","arrayKey":[{"keyA":"valueA","keyB":"valueB","keyC":[0,1,2]}]}
It has been proved that a regex approach does not work.
There are many pitfalls.
So I decided to create my own parser to get the work done
Edit: Attention! There is a mistake in the following code, causing escaped quotes being treated as normal ones, see my very answer to this question (also with further improvement)
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;
}
It seems to be working.
Just I would like to know
if the symbols it checks to insert the \n control character against are all symbols possible in a JSON text
and if there are some pitfalls that I am not able to see.