0

I have a text file in a format of json. Like this:

{"a":"1","b":"2"}

I may encounter in a situation like this:

{"a":"1","b":"2","a":"2"}

I read the text and saving it in a string called data and then create a jsonobject:

JSONObject json = new JSONObject(data);

I want that the value for json[data] will be "2" and not "1" How can i do this? Thanks

Parth
  • 791
  • 7
  • 17
Ori
  • 3
  • 1
  • I guess it will be help for you - https://stackoverflow.com/a/5306792/2504811 – adm1n Apr 14 '20 at 10:23
  • 1
    The JSON spec only says that names SHOULD be unique. Different libraries handle this differently. Some might support duplicate names, some might use the first occurrence, some might use the last occurrence, and some might throw an exception. It depends on the library used, so if you want different behavior, try using another library. – Andreas Apr 14 '20 at 10:31
  • i want to use the last occurence... do u know which library do it? JSONObject take the first occurence – Ori Apr 14 '20 at 10:35

2 Answers2

0

I think here, the key "name" would be better to contains ann array it's value, instead of having a number of keys "name".

{
  "name" : [ "Name1", "Name2", "Name3", ... ]
}
  • @Ori If you want the final value; I'm not quite sure, but in the building you are using now, you must crush the previous ones and give you the final value. – sadikkaplan Apr 14 '20 at 10:39
0

if you use net.sf.json then result is:

String str = "{\"a\":\"1\",\"b\":\"2\",\"a\":\"2\"}";
System.out.println(net.sf.json.JSONObject.fromObject(str).toString());

{"a":["1","2"],"b":"2"}

if you use com.alibaba.fastjson then result is:

String str = "{\"a\":\"1\",\"b\":\"2\",\"a\":\"2\"}";
System.out.println(com.alibaba.fastjson.JSONObject.parse(str).toString());

{"a":"2","b":"2"}

MrRiver
  • 16
  • 2