-1

I have this string:

[{"id":1,"code":"number","field":"Customer Number","value":"123456"},{"id":2,"code":"customerName","field":"Customer Name","value":"John"}]

And I'd like to get this values in java:

Customer number: 123456

Customer name: John

How can I do that?

Thank you for everything.

Warms regards.

shmosel
  • 49,289
  • 6
  • 73
  • 138

2 Answers2

0

Solution uses Jackson. Need to have databind, core and annotation jars of JACKSON for this. Make sure all 3 jars are of same version.

Create class for JSON as below:

public class Items {
    private int id;
    private String code;
    private String field;
    private String value;
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getCode() {
        return code;
    }
    public void setCode(String code) {
        this.code = code;
    }
    public String getField() {
        return field;
    }
    public void setField(String field) {
        this.field = field;
    }
    public String getValue() {
        return value;
    }
    public void setValue(String value) {
        this.value = value;
    }
}

Since the data you have is a JSON array, the way to deserialize is as below:

String jsonString = "your Json array";
ObjectMapper mapper = new ObjectMapper();
List<Data> objList = mapper.readValue(jsonString, new TypeReference<List<Data>>(){});
for (Data obj : objList) {
     //code.
}

If the data was a simple JSON object, the deserialization would be:

String jsonString = "your JSON";
ObjectMapper mapper = new ObjectMapper();
Data obj = mapper.readValue(jsonString, Data.class);
System.out.println(obj.getId());
HARDI
  • 394
  • 5
  • 12
0

You use JsonArray, which has documents here:

String yourString = "[{"id":1,"code":"number","field":"Customer Number","value":"123456"},{"id":2,"code":"customerName","field":"Customer Name","value":"John"}]"
JsonReader jr = new JsonReader(yourString);
JsonArray array = jr.readArray(); 
for(int ii=0; ii < array.length; ii++){
     JsonObject obj = array.getJsonObject(ii); 
     String id = obj.getString("id");
     String number = obj.getString("code");
     //and so on...
}

jr.close();
BlackHatSamurai
  • 23,275
  • 22
  • 95
  • 156