0

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
3
  • The code you posted does not produce any output. How is that output produced? As for building a JSONArray containing Strings, that looks fine. There is no need for the obj.put() to be in the loop; just do that once. Commented Nov 5, 2015 at 16:34
  • Okay...but any hint on modifying name-value pair names?? Commented Nov 5, 2015 at 16:45
  • JSONArray is not a name-value pair type of structure. A Map is, or a JSONObject. Is obj a Map or something? You don't show its declaration. Commented Nov 5, 2015 at 17:18

1 Answer 1

2

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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.