- Examples
- Full Data Binding (POJO) Example
- Simple Data Binding Example
- Data Binding with Generics
- Three Model Example
- Streaming API Example
- Full Data Binding(POJO)
Example
- Jackson's org.codehaus.jackson.map.ObjectMapper "just works" for mapping JSON data into plain old Java objects ("POJOs").
- Json data
{
"name" : { "first" : "Joe", "last" : "Sixpack" },
"gender" : "MALE",
"verified" : false,
"userImage" : "Rm9vYmFyIQ=="
}
- User Instance로의 변환
ObjectMapper mapper = new ObjectMapper(); // can reuse, share globally
User user = mapper.readValue(new File("user.json"), User.class);
- 결과물(User.java)
public class User {
public enum Gender { MALE, FEMALE };
public static class Name {
private String _first, _last;
public String getFirst() { return _first; }
public String getLast() { return _last; }
public void setFirst(String s) { _first = s; }
public void setLast(String s) { _last = s; }
}
private Gender _gender;
private Name _name;
private boolean _isVerified;
private byte[] _userImage;
public Name getName() { return _name; }
public boolean isVerified() { return _isVerified; }
public Gender getGender() { return _gender; }
public byte[] getUserImage() { return _userImage; }
public void setName(Name n) { _name = n; }
public void setVerified(boolean b) { _isVerified = b; }
public void setGender(Gender g) { _gender = g; }
public void setUserImage(byte[] b) { _userImage = b; }
}
- Json data로의 변환
mapper.writeValue(new File("user-modified.json"), user);
- Simple Data Binding Example
Map<String,Object> userData = new HashMap<String,Object>();
Map<String,String> nameStruct = new HashMap<String,String>();
nameStruct.put("first", "Joe");
nameStruct.put("last", "Sixpack");
userData.put("name", nameStruct);
userData.put("gender", "MALE");
userData.put("verified", Boolean.FALSE);
userData.put("userImage", "Rm9vYmFyIQ==");
- Json data로의 변환
mapper.writeValue(new File("user-modified.json"), userData);
- Concrete Java types that Jackson will use for simple data binding are:
JSON Type
Java Type
object
LinkedHashMap<String,Object>
array
ArrayList<Object>
string
String
number (no fraction)
Integer, Long or BigInteger (smallest applicable)
number (fraction)
Double (configurable to use BigDecimal)
true|false
Boolean
null
null
- Data Binding with Generics
- 제네릭을 사용하기 위해서는 TypeReference를 이용한다.
Map<String,User> result = mapper.readValue(src, new TypeReference<Map<String,User>>() { });
- 만약 Map.class만을 사용한다면 형이 지정되지 않는 Map<?, ?>으로 바인딩 된다.
- 다른 방법으로는, v1.3 이후부터는 TypeFactory를 이용할 수 있다.
- Tree Model Example
- ObjectMapper를 이용해 Tree Node를 만들고 Json으로 변환.
ObjectMapper m = new ObjectMapper();
// can either use mapper.readTree(JsonParser), or bind to JsonNode
JsonNode rootNode = m.readValue(new File("user.json"), JsonNode.class);
// ensure that "last name" isn't "Xmler"; if is, change to "Jsoner"
JsonNode nameNode = rootNode.path("name");
String lastName = nameNode.path("last").getTextValue().
if ("xmler".equalsIgnoreCase(lastName)) {
((ObjectNode)nameNode).put("last", "Jsoner");
}
// and write it out:
m.writeValue(new File("user-modified.json"), rootNode);
- Tree Node의 생성
TreeMapper treeMapper = new TreeMapper();
ObjectNode userOb = treeMapper.objectNode();
Object nameOb = userRoot.putObject("name");
nameOb.put("first", "Joe");
nameOb.put("last", "Sixpack");
userOb.put("gender", User.Gender.MALE.toString());
userOb.put("verified", false);
byte[] imageData = getImageData(); // or wherever it comes from
userOb.put("userImage", imageData);
- (NOTE: with Jackson 1.2 you can use ObjectMapper directly, using ObjectMapper.createObjectNode() to create userOb
Streaming API Example
- WriteJSON.java 작성
- ObjectMapper를 쓰는 것보다 다소 빠르다. 그러나 손이 많이 간다는 것!
- 이 방법을 쓸 일은 거의 없겠지…..
- Parsing
- JsonParser.readValueAs()
- JsonParser.readValueAsTree()
- JsonGenerator.writeObject()
- JsonGenerator.writeTree()
JsonFactory f = new JsonFactory(); JsonGenerator g = f.createJsonGenerator(new File("user.json"));
g.writeStartObject(); g.writeObjectFieldStart("name"); g.writeStringField("first", "Joe"); g.writeStringField("last", "Sixpack"); g.writeEndObject(); // for field 'name' g.writeStringField("gender", Gender.MALE); g.writeBooleanField("verified", false); g.writeFieldName("userImage"); // no 'writeBinaryField' (yet?) byte[] binaryData = ...; g.writeBinary(binaryData); g.writeEndObject(); g.close(); // important: will force flushing of output, close underlying output stream |
JsonFactory f = new JsonFactory(); JsonParser jp = f.createJsonParser(new File("user.json")); User user = new User(); jp.nextToken(); // will return JsonToken.START_OBJECT (verify?) while (jp.nextToken() != JsonToken.END_OBJECT) { String fieldname = jp.getCurrentName(); jp.nextToken(); // move to value, or START_OBJECT/START_ARRAY if ("name".equals(fieldname)) { // contains an object Name name = new Name(); while (jp.nextToken() != JsonToken.END_OBJECT) { String namefield = jp.getCurrentName(); jp.nextToken(); // move to value if ("first".equals(namefield)) { name.setFirst(jp.getText()); } else if ("last".equals(namefield)) { name.setLast(jp.getText()); } else { throw new IllegalStateException("Unrecognized field '"+fieldname+"'!"); } } user.setName(name); } else if ("gender".equals(fieldname)) { user.setGender(Gender.valueOf(jp.getText())); } else if ("verified".equals(fieldname)) { user.setVerified(jp.getCurrentToken() == JsonToken.VALUE_TRUE); } else if ("userImage".equals(fieldname)) { user.setUserImage(jp.getBinaryValue()); } else { throw new IllegalStateException("Unrecognized field '"+fieldname+"'!"); } } jp.close(); // ensure resources get cleaned up timely and properly |
-
추가적으로, 다음의 메소드로 JsonParser,
JsonGenerator에서 데이터 바인딩이나 Tree Model을 사용할 수 있다.
'Programming > Java' 카테고리의 다른 글
JAVA JSON 라이브러리 Jackson 사용법 (0) | 2014.09.11 |
---|---|
Spring에서 Json으로의 입출력 정리 (0) | 2014.09.11 |
Jackson Tutorial - 1 (0) | 2014.09.11 |
Jackson How-To: Ignoring Unknown Properties (0) | 2014.09.11 |
파싱(Parsing)강좌 (0) | 2014.05.23 |
댓글