0

Core Json–JSON和Java

Posted by 撒得一地 on 2016年4月20日 in JSON

Jackson (http://jackson.codehaus.org/) 库是一个流行的以Java为基础的JSON API。这里有一个如何编译一个地址对象为JSON对象,或者如何将JSON对象解析为地址对象的例子。

import java.io.Writer;
import java.io.StringWriter;
import org.codehaus.jackson.map.ObjectMapper;

public class Address {
private String line1;

private String city;

private String stateOrProvince;

private String zipOrPostalCode;

private String country;

public Address() {}

public String getLine1() {

return line1;
}

public void setLine1(line1) {
   this.line1 = line1;
}

// Remaining getters and setters ...
}

Address addrOut = new Address();

// Call setters to populate addrOut …

ObjectMapper mapper = new ObjectMapper(); 

// Reuse this.

// Marshal Address object to JSON String.

Writer writer = new StringWriter();

mapper.writeValue(writer, addrOut);

System.out.println(writer.toString());

// Unmarshal Address object from JSON String.

String addrJsonStr = 
"{" +
"\"address\" : {" +
"\"line1\" : \"555 Main Street\"," +
"\"city\" : \"Denver\","
"\"stateOrProvince\" : \"CO\","
"\"zipOrPostalCode\" : \"80202\"," +
"\"country\" : \"USA\"" +
"}" +
"}";

Address addrIn = mapper.readValue(addrJsonStr, Address.class);

除了Jackson外,也包含其他著名的以java为基础的JSON APIs。

上一篇:

下一篇:

相关推荐

发表评论

电子邮件地址不会被公开。 必填项已用*标注

3 + 5 = ?

网站地图|XML地图

Copyright © 2015-2017 技术拉近你我! All rights reserved.
闽ICP备15015576号-1,版权所有©psz.