Core Json–JSON和Java
Posted by 撒得一地 on 2016年4月20日 in JSON
上一篇: Core Json–JSON和Ajax
下一篇: Core Json–JSON和Ruby
科学上网 轻松上Google | 修改host解决Google打不开
Jackson () 库是一个流行的以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。
... other posts by psz1992