how to convert JSONArray to List of Object using camel-jackson

后端 未结 5 1766
Happy的楠姐
Happy的楠姐 2020-12-23 09:51

Am having the String of json array as follow

{\"Compemployes\":[
    {
        \"id\":1001,
        \"name\":\"jhon\"
        },
        {
                \"         


        
相关标签:
5条回答
  • 2020-12-23 10:13

    I had similar json response coming from client. Created one main list class, and one POJO class.

    0 讨论(0)
  • 2020-12-23 10:23
    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");
    

    Your arr would looks like: [ { "id":1001, "name":"jhon" }, { "id":1002, "name":"jhon" } ] You can use:

    arr.getJSONObject(index)
    

    to get the objects inside of the array.

    0 讨论(0)
  • 2020-12-23 10:27

    I also faced the similar problem with JSON output format. This code worked for me with the above JSON format.

    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());
            }
        }
    
    }
    
    0 讨论(0)
  • 2020-12-23 10:32

    The problem is not in your code but in your json:

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

    this represents an object which contains a property Compemployes which is a list of Employee. In that case you should create that object like:

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

    and to deserialize the json simply do:

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

    If your json should directly represent a list of employees it should look like:

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

    Last remark:

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

    TypeFactory.collectionType is deprecated you should now use something like:

    List<Employee> list = mapper.readValue(jsonString,
    TypeFactory.defaultInstance().constructCollectionType(List.class,  
       Employee.class));
    
    0 讨论(0)
  • 2020-12-23 10:34
    /*
     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();
     }
    }
    
    0 讨论(0)
提交回复
热议问题