有没有办法从json响应中创建bean类? [英] Is there a way to create the bean class from a json response

查看:84
本文介绍了有没有办法从json响应中创建bean类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将JSON转换为Java



上面的问题是参考了上述线程中描述的内容。有很多API提供了以XML或JSON格式返回响应的灵活性。 **我想知道是否有办法自动构造对应于JSON响应的java bean。 **

解决方案

可以说你得到一个像

的对象

<$ p $
name:Java 6 Greatest Hits,
Author:Jim Bob Jones,
price :10.25
},
{
name:如何养一只山羊,
作者:帕克斯顿爵士,
价格: 55.97
},
{
name:雪 - 它很冷,
作者:White博士,
价格: 9.99
}
]

你想要一个像

  public class Book {
private String author;
私人字符串名称;
私人数字价格
}

与getter和setters
One选项是使用像 JSONGen 这样的服务,它将创建该类。您需要首先使用它,并将生成的代码包含在您的项目中。
另一种选择是使用javassist或CGLib动态生成类,但除非使用反射来访问它的成员,否则该类将无用,所以即使它 是类,它也会行为就像一个非常恼人的地图。绝不会这么简单,使用 JSONObject


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. **

解决方案

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

这篇关于有没有办法从json响应中创建bean类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆