Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
485 views
in Technique[技术] by (71.8m points)

spring - java duplicate key in same json object

I am trying to parse a JSON response using jsonObject library in Java, but receiving exception with duplicated key. I need to parse this JSON as it is, without any loop and without any conversion. Some solution stated that I have to convert those values to array, so I need your suggestion. Is there any library that can parse my json which has duplicated key without any change? This is my code :

BufferedReader in = new BufferedReader(
        new InputStreamReader(c.getInputStream()));  //stream to resource
    
String inputLine;
StringBuffer res = new StringBuffer();
    
while ((inputLine = in.readLine()) != null) {
    res.append(inputLine);
}
    
JSONObject json = new JSONObject(res.toString());
    

my error response :

Exception in thread "main" org.json.JSONException: Duplicate key "Account"
    at org.json.JSONObject.putOnce(JSONObject.java:1121)
    at org.json.JSONObject.<init>(JSONObject.java:208)
    at org.json.JSONTokener.nextValue(JSONTokener.java:362)
    at org.json.JSONObject.<init>(JSONObject.java:208)
    at org.json.JSONTokener.nextValue(JSONTokener.java:362)
question from:https://stackoverflow.com/questions/65914310/java-duplicate-key-in-same-json-object

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

you can make use of net.sf.json.JSONObject. It will accept JSON with the duplicate key.

This library will retain the duplicated values by storing them into arrays. If multiple same keys are available it will create one key with all the values as Array.

And also the coding part is just a single line. Once you parsed the json using net.sf.json.JSONObject then you can supply this to jackson library.

JSONObject jsonObject = JSONObject.fromObject( "{ "a": "a", "a": { "b": {},"b": true}}" );

System.out.println( "net.sf.json.JSONObject: " + jsonObject );

JsonNode jsonNode = new ObjectMapper().readTree( jsonObject.toString() );

System.out.println( "com.fasterxml.jackson.databind.JsonNode" + jsonNode );

Output:

net.sf.json.JSONObject: {"a":["a",{"b":[{},true]}]}

com.fasterxml.jackson.databind.JsonNode{"a":["a",{"b":[{},true]}]}

Maven dependency of net.sf.json

<dependency>
    <groupId>net.sf.json-lib</groupId>
    <artifactId>json-lib</artifactId>
    <version>2.4</version>
    <classifier>jdk15</classifier>
</dependency>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...