Search code examples
javajsonobjectmapper

Can not get Java object from JSON string(with inner arrays)


I'm trying to get Java Object from JSON string that has inner arrays, there are pretty same questions, but none couldn't solve my problem. Now in console i get MethodPackage.JsonDeserialize@6580cfdd (I'm doing with objectmapper) My aim is to get separately values in json to do some manupulations

below is my full code:

JSONstring:
{
"status": 1,
"message": "ok",
"sheduleCod": "NOST_A_Persons_m_noaccum",
"algorithms": [{
    "cod": "No_st_alg_1",
    "kcp": "U6000427",
    "dtBeg": "2017-11-01 00:00:00",
    "dtEnd": "2017-12-01 00:00:00"
}, {
    "cod": "No_st_alg_2",
    "kcp": "U6000427",
    "dtBeg": "2017-11-01 00:00:00",
    "dtEnd": "2017-12-01 00:00:00"
}, {
    "cod": "No_st_alg_3",
    "kcp": "U6000427",
    "dtBeg": "2017-11-01 00:00:00",
    "dtEnd": "2017-12-01 00:00:00"
}]
}

          Main.class

String jsonString = response.toString();
JsonDeserialize deserialize = objectMapper.readValue(jsonString, JsonDeserialize.class);
System.out.println(deserialize);}

JsonDeserialize.class 
public class JsonDeserialize {
private String status;
private String message;
private String sheduleCod;
private List<Algorithm> algorithms;

            in JsonDeserialize.class 

public class JsonDeserialize {
private String status;
private String message;
private String sheduleCod;
private List<Algorithm> algorithms;
public JsonDeserialize(String status, String message, String sheduleCod, List<Algorithm> algorithms) {
    this.status = status;
    this.message = message;
    this.sheduleCod = sheduleCod;
    this.algorithms = algorithms;
}

..... and then getters and setters

                  Algorithm.class

public class Algorithm {
private String cod;
private String kcp;
private String dtBeg;
private String dtEnd;

public Algorithm(String cod, String kcp, String dtBeg, String dtEnd) {
    this.cod = cod;
    this.kcp = kcp;
    this.dtBeg = dtBeg;
    this.dtEnd = dtEnd;
}
public Algorithm () {

}

Solution

  • The output MethodPackage.JsonDeserialize@6580cfdd means that you print the reference and not the values of the object.

    To fix this problem override the toString method within the JsonDeserialize class like the following:

    @Override
    public String toString() {
        String values = ""; // you could also use a StringBuilder here
        values += "Status: " + status + "\n";
        values += "Message: " + message + "\n";
        // ....
        return values;
    }
    

    or use:

    System.out.println(deserialize.getStatus())
    System.out.println(deserialize.getMessage());
    // ...