Deserialize JSON in Jackson where key is a value

时间:2018-03-09 19:16:02

标签: java json jackson json-deserialization

{
  {
      "1234": {
          "name": "bob"
      }
  },
  {
      "5678": {
          "name": "dan"
      }
  }
}

I have a class representing name (and other fields, I've just made it simple for this question). But the each element is key'd with the id of the person.

I've tried several things including:

class Name {
     String Name;
     //getter and setter
}
class NameId {
     String id;
     Name name;
     //getter and setters
}

//json is the string containing of the above json
ArrayList<NameId> map = objectMapper.readValue(json, ArrayList.class);
for (Object m : map) {
    LinkedHashMap<String, NameId> l = (LinkedHashMap)m;
            Map<String, NameId> value = (Map<String, NameId>) l;

            //System.out.println(l);
            //System.out.println(value);
            for (Object key : value.keySet()) {
                System.out.println("key: " + key);
                System.out.println("obj: " + value.get(key));

                NameId nameId = (NameId)value.get(key);

            }
}

The problem I have is it doesn't allow that cast to NameId. The error I get is:

java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to NameId

Any ideas on the best way to parse such a json string like this properly?

4 个答案:

答案 0 :(得分:1)

你的json格格不入。你需要它周围的方括号,否则它不被认为是一个json数组。如果你的json看起来像(例如)

false

您可以为对象映射器编写自定义反序列化器。请参阅下面的工作示例:

[
    {
        "1234" : {
            "name" : "dan"
        }
    },
    {
        "5678" : {
            "name" : "mike"
        }
    }
]

答案 1 :(得分:0)

试试这个

Iterator<String> iterator1 =outerObject.keys();
while(iterator1.hasNext())
{
JsonObject innerObject=outerObject.getJsonObject(iterator1.next());
Iterator<String> iterator2=innerObject.keys();
while(iterator2.hasNext()){
String name=innerObject.getString(iterator2.next());
}
} 

答案 2 :(得分:0)

你的json无效。也许有点不同:

{
    "1234": {
        "name": "bob"
    },
    "5678": {
        "name": "dan"
    }
}

你可以建模如下:

class Person {
    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

而不是尝试使用列表,而是使用地图:

Map<Integer, Person> map = new ObjectMapper().readValue(json,
    TypeFactory.defaultInstance()
            .constructMapType(Map.class, Integer.class, Person.class));

答案 3 :(得分:0)

不需要自定义反序列化器。

首先,json文件为@klaimmore建议(名为test.json):

{
    "1234": {
        "name": "bob"
    },
    "5678": {
        "name": "dan"
    }
}

其次。这是2个单独的类文件:

@JsonDeserialize
public class Name {
    String name;

    public Name(String name) {
        this.name = name;
    }
    /**
     * @return the name
     */
    public String getName() {
        return name;
    }

    /**
     * @param name the name to set
     */
    public void setName(String name) {
        this.name = name;
    }
}

@JsonDeserialize
public class NameId {
    Name name;
    String id;
    /**
     * @return the id
     */
    public String getId() {
        return id;
    }
    /**
     * @param id the id to set
     */
    public void setId(String id) {
        this.id = id;
    }
    /**
     * @return the name
     */
    public Name getName() {
        return name;
    }
    /**
     * @param name the name to set
     */
    public void setName(Name name) {
        this.name = name;
    }
}

和额外的简单json解析器类。

public class JsonParser {

    /**
     * @param args
     * @throws IOException 
     */
    public static void main(String[] args) throws IOException {

        String jsonString = new String(Files.readAllBytes(Paths.get("test.json")));
        ObjectMapper mapper = new ObjectMapper();
        Map<String,NameId> nameIdList = mapper.readValue(jsonString, new TypeReference<Map<String,NameId>>(){});
        nameIdList.entrySet().forEach(nameIdEntry -> System.out.println("name id is: " + nameIdEntry.getKey() + 
                " and name is: " + nameIdEntry.getValue().getName().getName()));

    }

}

也。这几乎是How to convert json string to list of java objects的骗局。你应该读这个。