skip to Main Content

I have a JSON file which looks like:

{
  "caseNumber": "kblndw896",
  "features": [
    {
         "id1": "wad12jkb",
         "id2": "jBgioj",
         "id3": "jabd8&",
         "limit": "500000",
         "M1": "333487.2",
         "M2": "339259.88",
         "M3": "316003.84",
         "M4": "219097.12",
         "M5": "393842.98",
         "M6": "498684.1",
         "M7": "1074002.44",
         "M8": "437211.19",
         "M9": "444842.35",
         "M10": "657756.22",
         "M11": "571928.78",
         "M12": "230378.06"
      }
  ]
}

Now I’m trying to import this file and put in the POJO class called Payload, which has features POJO class as child. Now when I import using ObjectMapper:

ObjectMapper mapper = new ObjectMapper();
mapper.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true);
Payload payload= mapper.readValue(new File("filepath\file.json"),
                Payload.class);

then I’m getting this imported in the payload POJO class, but the values for keys in features array has null value for all the keys.

Example, the imported data is:

{
  "caseNumber": "kblndw896",
  "features": [
    {
      "id1": null,
      "id2": "null",
      "id3": "null",
      "limit": null,
      "m7": null,
      "m6": null,
      "m9": null,
      "m4": null,
      "m11": null,
      "m8": null,
      "m2": null,
      "m12": null,
      "m1": null,
      "m3": null,
      "m5": null,
      "m10": null
    }
  ]
}

How can I get values from file?

Tried:

ObjectMapper mapper = new ObjectMapper();
mapper.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true);
Payload payload= mapper.readValue(new File("filepath\file.json"),
                Payload.class);

Expected:

{
  "caseNumber": "kblndw896",
  "features": [
    {
         "id1": "wad12jkb",
         "id2": "jBgioj",
         "id3": "jabd8&",
         "limit": "500000",
         "M1": "333487.2",
         "M2": "339259.88",
         "M3": "316003.84",
         "M4": "219097.12",
         "M5": "393842.98",
         "M6": "498684.1",
         "M7": "1074002.44",
         "M8": "437211.19",
         "M9": "444842.35",
         "M10": "657756.22",
         "M11": "571928.78",
         "M12": "230378.06"
      }
  ]
}

2

Answers


  1. I would do it this way:

    This is class Features

    public class Features {
        private String id1;
        private String id2;
        private String id3;
        private String limit;
        private String m1;
        private String m2;
        private String m3;
        private String m4;
        private String m5;
        private String m6;
        private String m7;
        private String m8;
        private String m9;
        private String m10;
        private String m11;
        private String m12;
    
        // getters and setters below
    }
    

    This is class Payload

    public class Payload {
        private String caseNumber;
        private List<Features> features;
    
        // getters and setters below
    }
    

    And finally:

    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true);
    Payload payload = objectMapper.readValue(new File("filepath\file.json"), Payload.class);
    System.out.println(payload);
    
    Login or Signup to reply.
  2. You can try the provided method below. It makes use of the org.json.simple-1.1.1.jar library which you can download from here:

    The getKeyValuesFromJsonArray() Method:

    /**
     * Requires the json-simple-1.1.1.jar library.<b>Example Usage:</b>
     * <pre>
     * {@code
     * String jsonArrayData = "{     "count" : 2,n"
     *           + "n"
     *           + "     "elements" : [n"
     *           + "n"
     *           + "         {             "firstname" : "XXXXXXXXXX",             "lastname" : "A22"         },n"
     *           + "n"
     *           + "         {             "firstname" : "YYYYYYYYYY",             "lastname" : "A23"         }     n"
     *           + "n"
     *           + "]n"
     *           + "n"
     *           + "}";
     *
     *   List<String> data = getKeyValuesFromJsonArray(jsonArrayData, "firstname", "lastname");
     *
     *   for (String s : data) {
     *       System.out.println(s);
     *   } }</pre>
     *
     * @param jsonArrayString (String) The JSON String.<br>
     *
     * @param arrayKeyName    (String) The Key name for the start of the JSon
     *                        Array. In the example above the array key name is:
     *                        "elements".<br>
     *
     * @param elementKeys     (String varArgs OR String[] Array) Supply the key
     *                        names you would like to have the values for. This
     *                        can be supplied individually as comma delimited
     *                        Strings (as shown in the example above) or within
     *                        a String[] array.<br>
     *
     * @return ({@code List<String>}) Each array element (data group) contained
     *         within the JSON String is a individual, comma delimited string
     *         within the List.
     */
    public static List<String> getKeyValuesFromJsonArray(String jsonArrayString, String arrayKeyName, String... elementKeys) {
        java.util.List<String> list = new java.util.ArrayList<>();
    
        JSONParser parser = new JSONParser();
        Object obj = null;
        try {
            obj = parser.parse(jsonArrayString);
        }
        catch (ParseException ex) {
            Logger.getLogger("getKeyValuesFromJsonArray() Method Error!").log(Level.SEVERE, null, ex);
        }
        // A JSON object. Key value pairs are unordered. JSONObject supports java.util.Map interface.
        JSONObject jsonObject = (JSONObject) obj;
        // A JSON array. JSONObject supports java.util.List interface.
        JSONArray elements = (JSONArray) jsonObject.get(arrayKeyName);
        StringBuilder sb = new StringBuilder("");
        elements.forEach(e -> {
            JSONObject element = (JSONObject) e;
            for (String str : elementKeys) {
                if (!sb.toString().isEmpty()) {
                    sb.append(", ");
                }
                sb.append(element.get(str).toString());
            }
            list.add(sb.toString());
            sb.setLength(0);
        });
        return list;
    }
    

    How you might use the above method:

    /*
     The code below makes use of the `org.json.simple-1.1.1.jar` file. 
     You can download it from here: 
     https://code.google.com/archive/p/json-simple/downloads
    */
        
    // Read in the JSON file as a Single string as shown below:
    String json = "{n"
            + "  "caseNumber": "kblndw896",n"
            + "  "features": [n"
            + "    {n"
            + "         "id1": "wad12jkb",n"
            + "         "id2": "jBgioj",n"
            + "         "id3": "jabd8&",n"
            + "         "limit": "500000",n"
            + "         "M1": "333487.2",n"
            + "         "M2": "339259.88",n"
            + "         "M3": "316003.84",n"
            + "         "M4": "219097.12",n"
            + "         "M5": "393842.98",n"
            + "         "M6": "498684.1",n"
            + "         "M7": "1074002.44",n"
            + "         "M8": "437211.19",n"
            + "         "M9": "444842.35",n"
            + "         "M10": "657756.22",n"
            + "         "M11": "571928.78",n"
            + "         "M12": "230378.06"n"
            + "      }n"
            + "  ]n"
            + "}";
    
    /* Provide the Key Names you want to get values for 
       from each JSON array group named "features" (in 
       this particular case, all of them):          */
    String[] keys = {"id1", "id2", "id3", "limit", "M1", "M2", "M3", "M4",
                     "M5", "M6", "M7", "M8", "M9", "M10", "M11", "M12"};
    
    String jsonArrayKeyName = "features";
    
    // Get the desired JSON array data...
    List<String> list = getKeyValuesFromJsonArray(json, jsonArrayKeyName, keys);
    
    // If nothing was acquired...get outta here.
    if (list.isEmpty()) {
        return;
    }
    
    /* Declare a List Interface of Feature (see the `Feature` class).
       This List will hold all instances of Feature pulled from the
       JSON Array:        */
    List<Feature> fList = new ArrayList<>();
    
    for (String keyValue : list) {
        /* Split the current `list` element acquired from the 
           getKeyValuesFromJsonArray() method...          */
        String[] values = keyValue.split(",\s*");
            
        /* Fill variables that will be used for the Feature class 
           constructor so to create a Feature Instance:        */
        // Do whatever you want to do here for defaults (if at all)...
        String id1 = values[0].isEmpty() ? "N/A" : values[0];
        String id2 = values[1].isEmpty() ? "N/A" : values[1];
        String id3 = values[2].isEmpty() ? "N/A" : values[2];
        int limit = values[3].isEmpty() ? 0 : Integer.parseInt(values[3]);
        double m1 = values[4].isEmpty() ? 0.0d : Double.parseDouble(values[4]);
        double m2 = values[5].isEmpty() ? 0.0d : Double.parseDouble(values[5]);
        double m3 = values[6].isEmpty() ? 0.0d : Double.parseDouble(values[6]);
        double m4 = values[7].isEmpty() ? 0.0d : Double.parseDouble(values[7]);
        double m5 = values[8].isEmpty() ? 0.0d : Double.parseDouble(values[8]);
        double m6 = values[9].isEmpty() ? 0.0d : Double.parseDouble(values[9]);
        double m7 = values[10].isEmpty() ? 0.0d : Double.parseDouble(values[10]);
        double m8 = values[11].isEmpty() ? 0.0d : Double.parseDouble(values[11]);
        double m9 = values[12].isEmpty() ? 0.0d : Double.parseDouble(values[12]);
        double m10 = values[13].isEmpty() ? 0.0d : Double.parseDouble(values[13]);
        double m11 = values[14].isEmpty() ? 0.0d : Double.parseDouble(values[14]);
        double m12 = values[15].isEmpty() ? 0.0d : Double.parseDouble(values[15]);
            
        // Create an instance of Feature and store in `fList`
        fList.add(new Feature(id1, id2, id3, limit, m1, m2, m3, m4,
                                m5, m6, m7, m8, m9, m10, m11, m12));
    }
        
    // Display gathered instances of Feature:
    int cntr = 0;  // The current literal instance number:
    for (Feature ftr : fList) {
        cntr++;
        System.out.println("Feature Instance #" + cntr + ":");
        System.out.println("====================");
        // We've add a `toString()` method in the Feature class: 
        System.out.println(ftr.toString());
    }
    

    The Feature Class:

    public class Feature {
    
        private String id1;
        private String id2;
        private String id3;
        private int limit;
        private double m1;
        private double m2;
        private double m3;
        private double m4;
        private double m5;
        private double m6;
        private double m7;
        private double m8;
        private double m9;
        private double m10;
        private double m11;
        private double m12;
    
        public Feature(String id1, String id2, String id3, int limit, double m1,
                double m2, double m3, double m4, double m5, double m6,
                double m7, double m8, double m9, double m10, double m11,
                double m12) {
            this.id1 = id1;
            this.id2 = id2;
            this.id3 = id3;
            this.limit = limit;
            this.m1 = m1;
            this.m2 = m2;
            this.m3 = m3;
            this.m4 = m4;
            this.m5 = m5;
            this.m6 = m6;
            this.m7 = m7;
            this.m8 = m8;
            this.m9 = m9;
            this.m10 = m10;
            this.m11 = m11;
            this.m12 = m12;
        }
    
        @Override
        public String toString() {
            String ls = System.lineSeparator();
            return "id1 = " + id1 + ls + "id2 = " + id2 + ls + "id3 = " + id3 + ls 
                    + "limit = " + limit + ls + "m1 = " + m1 + ls + "m2 = " + m2 + ls 
                    +  "m3 = " + m3 + ls + "m4 = " + m4 + ls + "m5 = " + m5 + ls 
                    + "m6 = " + m6 + ls + "m7 = " + m7 + ls + "m8 = " + m8 + ls 
                    + "m9 = " + m9 + ls + "m10 = " + m10 + ls + "m11 = " + m11 
                    + ls + "m12 = " + m12 + ls;
        }
    
        // Getters & Setters (in case you want them):
        public String getId1() {
            return id1;
        }
    
        public void setId1(String id1) {
            this.id1 = id1;
        }
    
        public String getId2() {
            return id2;
        }
    
        public void setId2(String id2) {
            this.id2 = id2;
        }
    
        public String getId3() {
            return id3;
        }
    
        public void setId3(String id3) {
            this.id3 = id3;
        }
    
        public int getLimit() {
            return limit;
        }
    
        public void setLimit(int limit) {
            this.limit = limit;
        }
    
        public double getM1() {
            return m1;
        }
    
        public void setM1(double m1) {
            this.m1 = m1;
        }
    
        public double getM2() {
            return m2;
        }
    
        public void setM2(double m2) {
            this.m2 = m2;
        }
    
        public double getM3() {
            return m3;
        }
    
        public void setM3(double m3) {
            this.m3 = m3;
        }
    
        public double getM4() {
            return m4;
        }
    
        public void setM4(double m4) {
            this.m4 = m4;
        }
    
        public double getM5() {
            return m5;
        }
    
        public void setM5(double m5) {
            this.m5 = m5;
        }
    
        public double getM6() {
            return m6;
        }
    
        public void setM6(double m6) {
            this.m6 = m6;
        }
    
        public double getM7() {
            return m7;
        }
    
        public void setM7(double m7) {
            this.m7 = m7;
        }
    
        public double getM8() {
            return m8;
        }
    
        public void setM8(double m8) {
            this.m8 = m8;
        }
    
        public double getM9() {
            return m9;
        }
    
        public void setM9(double m9) {
            this.m9 = m9;
        }
    
        public double getM10() {
            return m10;
        }
    
        public void setM10(double m10) {
            this.m10 = m10;
        }
    
        public double getM11() {
            return m11;
        }
    
        public void setM11(double m11) {
            this.m11 = m11;
        }
    
        public double getM12() {
            return m12;
        }
    
        public void setM12(double m12) {
            this.m12 = m12;
        }
    
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search