1

How to add multiple JSON array with same name in a JSON object?

I have tried

JSONObject jsonObject = new JSONObject(jsonHeader);

jsonObject.put("item", jsonArray1);
jsonObject.put("item", jsonArray2);

Log.i(TAG, jsonObject.toString());

and I get this result

{
  ...

  "item":{[
      jsonArray2
   ]}
}

but I want get the result contain all the jsonArray

{
  ...
  "item":{[
      jsonArray1
   ]},

  "item":{[
      jsonArray2
   ]}
 }

How can I do that?

Thanks :D

2
  • 1
    I think what you want is not a valid JSON object. Commented Jan 7, 2015 at 17:45
  • Why would you make arrays with same names anyway? Commented Jan 7, 2015 at 17:49

2 Answers 2

4

No. You cant. It is not allowed to create two keys with same name inside a JSON object. It is not included in JSON standards.

Sign up to request clarification or add additional context in comments.

Comments

0

If all items are called item, you should consider doing two layers of JSON arrays instead.

[
   [ "A" ],
   [ "B" ],
   [ "C" ]
]

If the entries can have different names, you should do something like wrap the named arrays in an object. This means a JSON Array containing an object, and the object containing another object with a name and a JSON Array.

[
    {
        "item":["A"]
    },
    {
        "item":["B"]
    },
]

I would avoid having multiple keys with the same value not just for JSON standard reasons, but also for the fact that it would give you unexpected and possibly inconsistent results with many JSON parsers. Don't just think of a JSON object as JSON, but also how it would end up as data in a programming language

Disclaimer: I never tried a 2D JSON Array before.

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.