5.Core Json – JSON和Java

最后更新于:2022-04-01 05:30:55

Jackson (http://jackson.codehaus.org/) 库是一个流行的以[Java](http://w3cschool.codecloud.net/java/java-hello-world.html)为基础的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。
';