Home > Blockchain >  How to read this json with GSON
How to read this json with GSON

Time:10-18

I am trying to consume a json through an api using Google's GSON library to be able to recover the data. I would like to be able to obtain the data of the CssValidation and Result key but it took hours and I have not been able to get it.

    {

"cssvalidation": {
"uri""https://www.mywebsite.com,
"checkedby": "http://www.w3.org/2005/07/css-validator",
"csslevel""css3",
"date""2021-10-17T05:07:38Z",
"timestamp""1634490458519",
"validity"false,

"result": {
"errorcount"7,
"warningcount"350
},
}
}

My code in java is this:

Gson gson = new Gson();
ApiResponse apiResponse = gson.fromJson(response.body().string(), ApiResponse.class);

    public class ApiResponse {
        private CssValidation validation;

    }

    public class CssValidation{
        public String uri;
        public String getUri() {
            return uri;
        }
    }

CodePudding user response:

You seem to be doing it right, but your Java object property keys need to match up exactly with the keys in the JSON.

Specifically, the name of the property validation needs to changed to cssvalidation, so like this:

Gson gson = new Gson();
ApiResponse apiResponse = gson.fromJson(response.body().string(), ApiResponse.class);

    public class ApiResponse {
        private CssValidation cssvalidation;

    }

    public class CssValidation{
        public String uri;
        public String getUri() {
            return uri;
        }
    }

Also, if the given JSON string is really what you get, then your JSON needs to be fixed, as pointed out by Lukas Ownen's answer

CodePudding user response:

There are some problems with your json string which you need to fix before attempting to parse it, the uri value quotation is not closed, and there is an additional comma after the result object, after fixing both you end up with the functional json text

{
  "cssvalidation": {
    "uri": "https://www.mywebsite.com",
    "checkedby": "http://www.w3.org/2005/07/css-validator",
    "csslevel": "css3",
    "date": "2021-10-17T05:07:38Z",
    "timestamp": "1634490458519",
    "validity": false,
    "result": {
      "errorcount": 7,
      "warningcount": 350
    }
  }
}

you can parse it with the JsonParser and get its elements in the following way

JsonObject root = JsonParser.parseString(resp).getAsJsonObject();       
JsonObject cssValidation = root.get("cssvalidation").getAsJsonObject();     
String uri = cssValidation.get("uri").getAsString();    

System.out.println(uri);

And you will get the following output

https://www.mywebsite.com
  • Related