Home > Software design >  how to deserealize JSON without field names
how to deserealize JSON without field names

Time:12-18

I invoke a REST service that returns a JSON, I'm trying to deserialize it (convert it into an entity) but the thing is that it doesn't have field names to match. The JSON is like this one:

{
    "text1": "",
    "text2": null,
    "days": [
        {
            "20211217": {
                "07:00": {
                    "id": "1187067",
                    "cupo": 9
                },
                "08:00": {
                    "id": "1187068",
                    "cupo": 10
                }
            }
        },
        {
            "20211219": {
                "07:00": {
                    "id": "1187077",
                    "cupo": 10
                },
                "08:00": {
                    "id": "1187078",
                    "cupo": 10
                }
            
            }
        }
    ]
}

As you could see it have some fields like text1, text2, days, id and cupo, the problem is how to map the date text (20211217,20211219) and hours text. How could I manipulate this data?

CodePudding user response:

You could model the JSON as follows:

import java.util.List;
import java.util.Map;

public class YourClass {
    private String text1;
    private String text2;
    private List<Map<String, Map<String, YourOtherClass>>> days;

    public YourClass(String text1, String text2, List<Map<String, Map<String, YourOtherClass>>> days) {
        this.text1 = text1;
        this.text2 = text2;
        this.days = days;
    }

    public String getText1() {
        return text1;
    }

    public void setText1(String text1) {
        this.text1 = text1;
    }

    public String getText2() {
        return text2;
    }

    public void setText2(String text2) {
        this.text2 = text2;
    }

    public List<Map<String, Map<String, YourOtherClass>>> getDays() {
        return days;
    }

    public void setDays(List<Map<String, Map<String, YourOtherClass>>> days) {
        this.days = days;
    }
}

And then the other class to model id and cupo as follows:

public class YourOtherClass {
    private String id;
    private int cupo;

    public YourOtherClass(String id) {
        this.id = id;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public int getCupo() {
        return cupo;
    }

    public void setCupo(int cupo) {
        this.cupo = cupo;
    }
}
  • Related