0

I need to create variable amount of JSON objects and based on the result set from a database query. States retrieving from mysql database. I am saving the response in JSON array but it is saving in multiple JSON objects like that:

    jString userid = rs2.getString("state");
    JSONObject mainObj = new JSONObject();
    JSONArray jsArray = new JSONArray();
    jsArray.put(userid );
    mainObj.put("states", jsArray);

With this output:

    {"states":["karnataka"]}
    {"states":["kerala"]}
    {"states":["chennai"]}

Can I get output in single JSON object like {"States":"karnataka","kerala","chennai"}?

2
  • it really depends on your JSON structure. you can structure it as a list: "States": [ "karnataka", "kerala", "chennai" ] Commented Mar 7, 2018 at 13:13
  • BTW, your proposed JSON structure is invalid. Commented Mar 7, 2018 at 13:23

1 Answer 1

1

You probably just got some code structure confused.

Try something like this:

JSONArray jsArray = new JSONArray();
JSONObject mainObj = new JSONObject();

//some kind of loop 
{
    jString userid = rs2.getString("state");
    jsArray.put(userid);
}
mainObj.put("states", jsArray);
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.