如何将POJO转换为JSON,反之亦然? [英] How to convert POJO to JSON and vice versa?
本文介绍了如何将POJO转换为JSON,反之亦然?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想知道是否有可用于将POJO对象转换为JSON对象的Java API,反之亦然。
I want to know if there is any Java API available to convert a POJO object to a JSON object and vice versa.
推荐答案
是的,有json.org。请查看 http://www.json.org/java/index.html
Yes, there is the json.org. Take a look at http://www.json.org/java/index.html
想象一下你有一个像这样的简单Java类:
[edited] Imagine that you have a simple Java class like this:
public class Person {
private String name;
private Integer age;
public String getName() { return this.name; }
public void setName( String name ) { this.name = name; }
public Integer getAge() { return this.age; }
public void setAge( Integer age ) { this.age = age; }
}
因此,要将其转换为JSon对象,它是非常简单。像这样:
So, to transform it to a JSon object, it's very simple. Like this:
import org.json.JSONObject;
public class JsonTest {
public static void main( String[] args ) {
Person person = new Person();
person.setName( "Person Name" );
person.setAge( 666 );
JSONObject jsonObj = new JSONObject( person );
System.out.println( jsonObj );
}
}
希望有所帮助。
这里有另一个例子,在这种情况下使用Jackson: https://brunozambiazi.wordpress.com/2015/08/15/working-with-json-in-java/ 合作
这篇关于如何将POJO转换为JSON,反之亦然?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文