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.

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.

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.