0

This Json

{
    "age":"23",
    "name":"srinivas",
    "blog":"A",
    "messages":["msg1","msg2","msg3"] 
}

I want convert a json to java class like this class and class use:

public class A
{
    private String name;

    private String age;

    private String blog;

    private String[] messages;

    public String getName ()
    {
        return name;
    }

    public void setName (String name)
    {
        this.name = name;
    }

    public String getAge ()
    {
        return age;
    }

    public void setAge (String age)
    {
        this.age = age;
    }

    public String getBlog ()
    {
        return blog;
    }

    public void setBlog (String blog)
    {
        this.blog = blog;
    }

}
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129

2 Answers2

0

No. You cant have class created automatically for you from your json.

However the below thing you might be needing that's related:

You need link

Excerpt from the link, below example code:

String carJson =
        "{ \"brand\" : \"Mercedes\", \"doors\" : 5," +
        "  \"owners\" : [\"John\", \"Jack\", \"Jill\"]," +
        "  \"nestedObject\" : { \"field\" : \"value\" } }";

ObjectMapper objectMapper = new ObjectMapper();


try {

    JsonNode node = objectMapper.readValue(carJson, JsonNode.class);

    JsonNode brandNode = node.get("brand");
    String brand = brandNode.asText();
    System.out.println("brand = " + brand);

    JsonNode doorsNode = node.get("doors");
    int doors = doorsNode.asInt();
    System.out.println("doors = " + doors);

    JsonNode array = node.get("owners");
    JsonNode jsonNode = array.get(0);
    String john = jsonNode.asText();
    System.out.println("john  = " + john);

    JsonNode child = node.get("nestedObject");
    JsonNode childField = child.get("field");
    String field = childField.asText();
    System.out.println("field = " + field);

} catch (IOException e) {
    e.printStackTrace();
}
jarvo69
  • 7,908
  • 2
  • 18
  • 28
0

You technically can create a class at runtime: see How to create a class dynamically in java or Creating classes dynamically with Java. However, if your code wants to use A in some way, it needs to be available during compilation. And if your code doesn't need to use A, why create it? You could implement some interface/extend some class which is available during compilation, but in your case there is no reasonable common interface and you could only access it using reflection.

A more reasonable alternative would be to generate a class from known JSON examples (or better, from some schema description) during your build process. Again, there are many ways to do this and you should search for one which fits your needs.

Community
  • 1
  • 1
Alexey Romanov
  • 167,066
  • 35
  • 309
  • 487