将json转换为object

时间:2018-01-15 13:15:49

标签: java json jackson

我正在尝试将下面的json转换为java bean,需要你的帮助

Sort.json

{
  "messages": [
    {
      "GG_RETAIL_BRANCH_SAVING_SELLER": [
        "hello jackson 1",
        "hello jackson 2",
        "hello jackson 3"
      ]
    },
    {
      "GG_RETAIL_CONNECT_SAVINGS_SELLER": [
        "hello jackson 4",
        "hello jackson 5",
        "hello jackson 6"
      ]
    }
  ]
}

My Bean看起来像

import java.io.Serializable;
import java.util.List;
import java.util.Map;

public class Sort implements Serializable{

    /**
     * 
     */
    private static final long serialVersionUID = 8122222228160190915L;
    /*  private String name;
    private int age;*/
    private Map<String,List<String>> messages;

    @Override
    public String toString() {
        return "AdamSort [messages=" + messages + "]";
    }

    public Map<String, List<String>> getMessages() {
        return messages;
    }

    public void setMessages(Map<String, List<String>> messages) {
        this.messages = messages;
    }
}

我的测试类是

import java.io.File;
import java.io.IOException;

import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;

public class JacksonExample {

    /**
     * @param args
     */
    public static void main(String[] args) {
        ObjectMapper mapper = new ObjectMapper();

        try {           
            Sort sort = mapper.readValue(new File("C:\\Sort.json"), Sort.class);
            System.out.println(sort);

        } catch (JsonGenerationException e) {
            e.printStackTrace();
        } catch (JsonMappingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

我看到的错误是

org.codehaus.jackson.map.JsonMappingException: Can not deserialize instance of java.util.LinkedHashMap out of START_ARRAY token
 at [Source: C:\Sort.json; line: 2, column: 3] (through reference chain: com.test.Sort["messages"])
    at org.codehaus.jackson.map.JsonMappingException.from(JsonMappingException.java:163)
    at org.codehaus.jackson.map.deser.StdDeserializationContext.mappingException(StdDeserializationContext.java:219)
    at org.codehaus.jackson.map.deser.StdDeserializationContext.mappingException(StdDeserializationContext.java:212)
    at org.codehaus.jackson.map.deser.std.MapDeserializer.deserialize(MapDeserializer.java:246)
    at org.codehaus.jackson.map.deser.std.MapDeserializer.deserialize(MapDeserializer.java:33)
    at org.codehaus.jackson.map.deser.SettableBeanProperty.deserialize(SettableBeanProperty.java:299)
    at org.codehaus.jackson.map.deser.SettableBeanProperty$MethodProperty.deserializeAndSet(SettableBeanProperty.java:414)
    at org.codehaus.jackson.map.deser.BeanDeserializer.deserializeFromObject(BeanDeserializer.java:697)
    at org.codehaus.jackson.map.deser.BeanDeserializer.deserialize(BeanDeserializer.java:580)
    at org.codehaus.jackson.map.ObjectMapper._readMapAndClose(ObjectMapper.java:2732)
    at org.codehaus.jackson.map.ObjectMapper.readValue(ObjectMapper.java:1817)
    at com.test.util.JacksonExample.main(JacksonExample.java:28)

请建议:

4 个答案:

答案 0 :(得分:2)

在查看JSON字符串时,messages是Map的列表。

Map<String,List<String>>替换为List<Map<String, List<String>>>中的Sort.java并试一试。

答案 1 :(得分:0)

您的JSON转换为:

public class Sort {
    private List<Message> messages;
}

public class Message {
    private List<String> GG_RETAIL_BRANCH_SAVING_SELLER;
}

所以你可以使用这样的类,或者为jackson写一个自定义的反序列化器。

更新:

好的,尝试使用反序列化器:

    ObjectMapper mapper = new ObjectMapper();

    try {
        SimpleModule module = new SimpleModule();
        module.addDeserializer(Sort.class, new SortDeserializer());
        mapper.registerModule(module);

这里是班级SortDeserializer

public class SortDeserializer extends StdDeserializer<Sort> {
    public SortDeserializer() { 
        this(null); 
    } 

    public SortDeserializer(Class<?> vc) { 
        super(vc); 
    }

    @Override
    public Sort deserialize(JsonParser jp, DeserializationContext dc)
            throws IOException, JsonProcessingException {
        Map<String,List<String>> messages = new HashMap<>();
        JsonNode node = jp.getCodec().readTree(jp);
        ArrayNode msgs = (ArrayNode)node.get("messages");
        for (JsonNode parm: msgs) {
            for (Iterator<String> it = parm.fieldNames(); it.hasNext(); ) {
                String key = it.next();
                ArrayNode values = (ArrayNode)parm.get(key);
                List<String> list = new ArrayList<>();
                for (JsonNode vnode: values) {
                    list.add(vnode.asText());
                }
                messages.put(key, list);
            }
        }
        Sort resp = new Sort();
        resp.setMessages(messages);
        return resp;
    }   
}

答案 2 :(得分:0)

根据json,java bean是不正确的。 它应该是:

import java.util.ArrayList;
import java.util.Map;

public class Sort {

    ArrayList<Map<String,ArrayList<String>>> messages;

    public ArrayList<Map<String, ArrayList<String>>> getMessages() {
        return messages;
    }

    public void setMessages(ArrayList<Map<String, ArrayList<String>>> messages) {
        this.messages = messages;
    }
}

答案 3 :(得分:-1)

稍微修改了JSON

{
  "messages": [
    {
      "group": "GG_RETAIL_BRANCH_SAVING_SELLER",
      "sortCode": [
        "hello jackson 1",
        "hello jackson 2",
        "hello jackson 3"
      ]
    },
    {
      "group": "GG_RETAIL_BRANCH_SAVING_SELLER",
      "sortCode": [
        "hello jackson 4",
        "hello jackson 5",
        "hello jackson 6"
      ]
    }
  ]
}

添加了一个新类:

import java.util.List;

public class Message {

    private String group;
    private List<String> sortCode;
    public String getGroup() {
        return group;
    }
    public void setGroup(String group) {
        this.group = group;
    }
    public List<String> getSortCode() {
        return sortCode;
    }
    public void setSortCode(List<String> sortCode) {
        this.sortCode = sortCode;
    }
    @Override
    public String toString() {
        return "{group:" + group + ", sortCode:" + sortCode + "}";
    }
}


import java.util.List;

public class Sort {

    private List<Message> messages;

    @Override
    public String toString() {
        return  messages + "";
    }

    public List<Message> getMessages() {
        return messages;
    }

    public void setMessages(List<Message> messages) {
        this.messages = messages;
    }
}

它似乎有效。