Reputation: 393
I have a string which follows a certain pattern and I want to write the substring into a JSON array object.
I have each substring in an array using regular expression.
Now I want to write all these substring in a json file using a jsonarray object.
I have been able to do it fine, but the name value pairs in json viewer shows
0 abcde
1 pqrs
I want to modify these names ( i.e. 0 and 1) to specific string. How to do it?
Below is my code.
String introduction="<p>abcde</p><p>pqrs</p><p>xyz</p>";
JSONArray intro_paragraphs = new JSONArray();
Matcher m = Pattern.compile(Pattern.quote("<p>")+ "(.*?)"+ Pattern.quote("</p>")).matcher(introduction);
while(m.find())
{
String match_intro = m.group(1);
intro_paragraphs.put(match_intro);
obj.put("Section_Detailed_Introduction", intro_paragraphs);
}
Output is:::
[]Section_Detailed_Introduction
0 abcde
1 pqrs
2 xys
I want:::
para_1 abcde
para_2 pqrs
para_3 xyz
Upvotes: 0
Views: 233
Reputation: 411
Make some minor modification on the code you can achieve this
String introduction="<p>abcde</p><p>pqrs</p><p>xyz</p>";
JSONObject intro_paragraphs = new JSONObject();
JSONObject obj=new JSONObject();
Matcher m = Pattern.compile(Pattern.quote("<p>")+ "(.*?)"+ Pattern.quote("</p>")).matcher(introduction);
int i=1;
String key="para_";
while(m.find())
{
String match_intro = m.group(1);
intro_paragraphs.put(key+i, match_intro);
i++;
}
obj.put("Section_Detailed_Introduction", intro_paragraphs);
Upvotes: 2