Search code examples
javagson

How to convert JSON to Java class using Gson's fromJson method?


I have a message in JSON and I want convert it to a Java object using the "fromJson" method of the Gson library.

How can I do this?

I have the message JSON in this format:

{
   "desc":[
      {
         "name":"id",
         "desc":{
            "ip_arduino":"value",
            "id_house":"value",
            "house_address":"value"
         }
      },
      {
         "name":"P1",
         "desc":{
            "field":"panel1",
            "value":0
         }
      },
      {
         "name":"P2",
         "desc":{
            "field":"panel3",
            "value":0
         }
      },
      {
         "name":"P3",
         "desc":{
            "field":"panel3",
            "value":0
         }
      },
      {
         "name":"P4",
         "desc":{
            "field":"panel4",
            "value":0
         }
      }
   ]
}

I have tried this, but it does not work. I have printed some value, but it is null:

jsonDesc.java file

public class jsonDesc {

    private ArrayList<Desc> desc = new ArrayList();
    
}

and Desc.java file

public class Desc {
    String name;
    desc desc;

    desc1 desc1;

    public class desc{
       String ip_arduino;
       String id_house;
       String house_address;
    }

    public class desc1{
        String name;
        desc desc;
        public class desc{
            String field;
            String value;
        }
    }

}

Solution

  • If you already have this in an object then it is simple as this

    Desc desc = new Gson().fromJson(jsonString, Desc.class);
    

    Also for creating class models don't waste time making your own... just use this: https://www.jsonschema2pojo.org/

    Saves headache and time