2

I'm trying to deserialize the following JSON which I'm obtaning from the Google Cloud Platform Translation API:

{
    "data": {
        "detections": [
            [
                {
                    "confidence": 0.394001841545105,
                    "isReliable": false,
                    "language": "en"
                }
            ],
            [
                {
                    "confidence": 0.25323036313056946,
                    "isReliable": false,
                    "language": "es"
                }
            ]
        ]
    }
}

But I don't know how to make the model. I've tried this:

private class DetectionModel {
    public Detection[] detections;
}

private class Detection {
    public String language;
    public Boolean isReliable;
    public Decimal confidence;
}

In order to later do:

DetectionModel model = (DetectionModel) JSON.deserialize(responseBody, DetectionModel.class);
model.detections[0].language;

But it's not exactly right. Can you guys help me define the DetectionModel correctly? I'm not sure how to do it since the list of "detections" doesn't have a property name.

The Documentation would be here.

1 Answer 1

3

json2apex generates this:

//
// Generated by JSON2Apex http://json2apex.herokuapp.com/
//

public class DetectionModel {

    public class DetectionModel {
        public Data data;
    }

    public class Data {
        public List<List<Detections>> detections;
    }

    public class Detections {
        public Double confidence;
        public Boolean isReliable;
        public String language;
    }


    public static DetectionModel parse(String json) {
        return (DetectionModel) System.JSON.deserialize(json, DetectionModel.class);
    }
}

that looks right to me with the array of arrays being represented by the list of lists List<List<Detections>> as arrays and lists are mostly interchangeable in Apex.

2
  • Oh, nice app. Thanks a lot Keith! I'm bookmarking that :-P Commented Jul 15, 2017 at 14:12
  • @JavierGarcíaManzano Yeah its a great time saver and gets the code right much more often than I do...
    – Keith C
    Commented Jul 15, 2017 at 14:12

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .