Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
140 views
in Technique[技术] by (71.8m points)

java - Is there a way to create the bean class from a json response

Converting JSON to Java

The above question is with reference to what has been described on the above thread. There are so many API(s) which provide the flexibility to return responses either in XML or JSON. **I would like to know if there is a way to automatically construct the java bean corresponding to a JSON response. **

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

lets say you get an object like

    [
        {
        "name":"Java 6 Greatest Hits",
        "Author":"Jim Bob Jones",
        "price":10.25
        },
        {
        "name":"How to raise a goat",
        "Author":"Sir Paxton",
        "price":55.97   
        },
        {
        "name":"Snow - It is cold",
        "Author":"Dr. White",
        "price":9.99    
        }
   ]

And you want a class like

public class Book{
    private String author;
    private String name;
    private Number price
}

with getters and setters One option is to use a service like JSONGen, which will create that class. You need to use it first, and include the generated code in your project. Another option could be dynamically generate the class using javassist or CGLib, but that class would be useless unless you use reflection to access its members, so even if it would be a class, it will behave like a really annoying Map. In no way will be better that simple using JSONObject


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...