【问题标题】:how to convert JSONArray to List of Object using camel-jackson如何使用骆驼杰克逊将 JSONArray 转换为对象列表
【发布时间】:2013-10-16 18:07:19
【问题描述】:

我的 json 数组字符串如下

{"Compemployes":[
    {
        "id":1001,
        "name":"jhon"
        },
        {
                "id":1002,
        "name":"jhon"
        }
]}

我想将此 jsonarray 转换为 List<Empolyee> 。为此,我添加了 maven 依赖项“camel-jackson”,并为员工编写了 pojo 类。但是当我尝试运行下面的代码时

 ObjectMapper mapper = new ObjectMapper();
 List<Employe> list = mapper.readValue(jsonString, TypeFactory.collectionType(List.class, Employe.class));

我遇到了以下异常。

org.codehaus.jackson.map.JsonMappingException: Can not deserialize instance of java.util.ArrayList out of START_OBJECT token
 at [Source: java.io.StringReader@43caa144; line: 1, column: 1]

有人可以告诉我缺少什么或做错了什么

【问题讨论】:

  • 如果我尝试使用“org.json”的依赖项,它会给我一个例外。
  • 我不确定它是否会起作用,但您可以尝试像这样配置对象映射器:mapper.configure(DeserializationConfig.Feature.UNWRAP_ROOT_VALUE, true)

标签: java json jackson apache-camel


【解决方案1】:

问题不在于您的代码,而在于您的 json:

{"Compemployes":[{"id":1001,"name":"jhon"}, {"id":1002,"name":"jhon"}]}

this 表示一个包含属性 Compemployes 的对象,该属性是 员工。在这种情况下,您应该像这样创建该对象:

class EmployeList{
    private List<Employe> compemployes;
    (with getter an setter)
}

反序列化 json 只需:

EmployeList employeList = mapper.readValue(jsonString,EmployeList.class);

如果您的 json 应该直接表示员工列表,它应该如下所示:

[{"id":1001,"name":"jhon"}, {"id":1002,"name":"jhon"}]

最后一句话:

List<Employee> list2 = mapper.readValue(jsonString, 
TypeFactory.collectionType(List.class, Employee.class));

TypeFactory.collectionType 已被弃用,您现在应该使用类似的东西:

List<Employee> list = mapper.readValue(jsonString,
TypeFactory.defaultInstance().constructCollectionType(List.class,  
   Employee.class));

【讨论】:

  • 感谢您的回复,但客户端仅以给定格式发送数据,所以有什么方法可以自动处理或需要处理它并操作字符串以获取您想要的格式告诉过吗?
  • 更新了我的回复:您应该使用 List compemployes 属性创建一个对象 x。
  • 您好,该方法有效。但我有如上所示的 json 格式,因此需要在进一步处理之前对其进行一些操作
  • 或者你可以创建一个中间对象 EmployeList 与成员 List compemployes
  • 嗯,我觉得在“EmployeList”类中​​还有更多工作要做,而不仅仅是添加“一些”getter 和 setter .. 并没有真正给出方向。当您尝试序列化到该类时,什么都不会发生。
【解决方案2】:
/*
 It has been answered in http://stackoverflow.com/questions/15609306/convert-string-to-json-array/33292260#33292260
 * put string into file jsonFileArr.json
 * [{"username":"Hello","email":"hello@email.com","credits"
 * :"100","twitter_username":""},
 * {"username":"Goodbye","email":"goodbye@email.com"
 * ,"credits":"0","twitter_username":""},
 * {"username":"mlsilva","email":"mlsilva@email.com"
 * ,"credits":"524","twitter_username":""},
 * {"username":"fsouza","email":"fsouza@email.com"
 * ,"credits":"1052","twitter_username":""}]
 */

public class TestaGsonLista {

public static void main(String[] args) {
Gson gson = new Gson();
 try {
    BufferedReader br = new BufferedReader(new FileReader(
            "C:\\Temp\\jsonFileArr.json"));
    JsonArray jsonArray = new JsonParser().parse(br).getAsJsonArray();
    for (int i = 0; i < jsonArray.size(); i++) {
        JsonElement str = jsonArray.get(i);
        Usuario obj = gson.fromJson(str, Usuario.class);
        //use the add method from the list and returns it.
        System.out.println(obj);
        System.out.println(str);
        System.out.println("-------");
    }
 } catch (IOException e) {
    e.printStackTrace();
 }
}

【讨论】:

  • 这个效率很低!
【解决方案3】:

我也遇到了 JSON 输出格式的类似问题。这段代码适用于我上面的 JSON 格式。

package com.test.ameba;

import java.util.List;

public class OutputRanges {
    public List<Range> OutputRanges;
    public String Message;
    public String Entity;

    /**
     * @return the outputRanges
     */
    public List<Range> getOutputRanges() {
        return OutputRanges;
    }

    /**
     * @param outputRanges the outputRanges to set
     */
    public void setOutputRanges(List<Range> outputRanges) {
        OutputRanges = outputRanges;
    }

    /**
     * @return the message
     */
    public String getMessage() {
        return Message;
    }

    /**
     * @param message the message to set
     */
    public void setMessage(String message) {
        Message = message;
    }

    /**
     * @return the entity
     */
    public String getEntity() {
        return Entity;
    }

    /**
     * @param entity the entity to set
     */
    public void setEntity(String entity) {
        Entity = entity;
    }
}

package com.test;


public class Range {
    public String Name;
    /**
     * @return the name
     */
    public String getName() {
        return Name;
    }
    /**
     * @param name the name to set
     */
    public void setName(String name) {
        Name = name;
    }

    public Object[] Value;
    /**
     * @return the value
     */
    public Object[] getValue() {
        return Value;
    }
    /**
     * @param value the value to set
     */
    public void setValue(Object[] value) {
        Value = value;
    }

}

package com.test.ameba;

import java.io.IOException;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JSONTest {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        String jsonString ="{\"OutputRanges\":[{\"Name\":\"ABF_MEDICAL_RELATIVITY\",\"Value\":[[1.3628407124839714]]},{\"Name\":\" ABF_RX_RELATIVITY\",\"Value\":[[\"CPD\",\"SL Limit\",\"Concat\",1,1.5,2,2.5,3]]},{\"Name\":\" ABF_Unique_ID_ERR\",\"Value\":[[\"CPD\",\"SL Limit\",\"Concat\",1,1.5,2,2.5,3]]},{\"Name\":\" ABF_FIRST_ERR\",\"Value\":[[\"CPD\",\"SL Limit\",\"Concat\",1,1.5,2,2.5,3]]},{\"Name\":\" ABF_AMEBA_ERR\",\"Value\":[[\"CPD\",\"SL Limit\",\"Concat\",1,1.5,2,2.5,3]]},{\"Name\":\" ABF_Effective_Date_ERR\",\"Value\":[[\"CPD\",\"SL Limit\",\"Concat\",1,1.5,2,2.5,3]]},{\"Name\":\" ABF_AMEBA_MODEL\",\"Value\":[[\"CPD\",\"SL Limit\",\"Concat\",1,1.5,2,2.5,3]]},{\"Name\":\" ABF_UC_ER_COPAY_ERR\",\"Value\":[[\"CPD\",\"SL Limit\",\"Concat\",1,1.5,2,2.5,3]]},{\"Name\":\" ABF_INN_OON_DED_ERR\",\"Value\":[[\"CPD\",\"SL Limit\",\"Concat\",1,1.5,2,2.5,3]]},{\"Name\":\" ABF_COINSURANCE_ERR\",\"Value\":[[\"CPD\",\"SL Limit\",\"Concat\",1,1.5,2,2.5,3]]},{\"Name\":\" ABF_PCP_SPEC_COPAY_ERR\",\"Value\":[[\"CPD\",\"SL Limit\",\"Concat\",1,1.5,2,2.5,3]]},{\"Name\":\" ABF_INN_OON_OOP_MAX_ERR\",\"Value\":[[\"CPD\",\"SL Limit\",\"Concat\",1,1.5,2,2.5,3]]},{\"Name\":\" ABF_IP_OP_COPAY_ERR\",\"Value\":[[\"CPD\",\"SL Limit\",\"Concat\",1,1.5,2,2.5,3]]},{\"Name\":\" ABF_PHARMACY_ERR\",\"Value\":[[\"CPD\",\"SL Limit\",\"Concat\",1,1.5,2,2.5,3]]},{\"Name\":\" ABF_PLAN_ADMIN_ERR\",\"Value\":[[\"CPD\",\"SL Limit\",\"Concat\",1,1.5,2,2.5,3]]}],\"Message\":\"\",\"Entity\":null}";
        ObjectMapper mapper = new ObjectMapper();
        OutputRanges OutputRanges=null;
        try {
            OutputRanges = mapper.readValue(jsonString, OutputRanges.class);
        } catch (JsonParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (JsonMappingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.println("OutputRanges :: "+OutputRanges);;
        System.out.println("OutputRanges.getOutputRanges() :: "+OutputRanges.getOutputRanges());;
        for (Range r : OutputRanges.getOutputRanges()) {
            System.out.println(r.getName());
        }
    }

}

【讨论】:

    【解决方案4】:
    private static String readAll(Reader rd) throws IOException {
        StringBuilder sb = new StringBuilder();
        int cp;
        while ((cp = rd.read()) != -1) {
          sb.append((char) cp);
        }
        return sb.toString();
      }
    
     String jsonText = readAll(inputofyourjsonstream);
     JSONObject json = new JSONObject(jsonText);
     JSONArray arr = json.getJSONArray("Compemployes");
    

    你的 arr 看起来像:[ { “身份证”:1001, “名称”:“约翰” }, { “身份证”:1002, “名称”:“约翰” } ] 您可以使用:

    arr.getJSONObject(index)
    

    获取数组内的对象。

    【讨论】:

      【解决方案5】:

      我收到了来自客户端的类似 json 响应。创建了一个主列表类和一个 POJO 类。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-09-10
        • 2012-05-18
        • 2022-01-03
        • 2017-10-03
        • 2018-07-25
        • 2023-04-07
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多