private void write(JsonGenerator jg, TwitterEntry entry) throws IOException { jg.writeStartObject(); // can either do "jg.writeFieldName(...) + jg.writeNumber()", or this: jg.writeNumberField("id", entry.getId()); jg.writeStringField("text", entry.getText()); jg.writeNumberField("fromUserId", entry.getFromUserId()); jg.writeNumberField("toUserId", entry.getToUserId()); jg.writeStringField("langugeCode", entry.getLanguageCode()); jg.writeEndObject(); jg.close(); }
private TwitterEntry read(JsonParser jp) throws IOException { // First: verify that we got "Json Object": if (jp.nextToken() != JsonToken.START_OBJECT) { throw new IOException("Expected data to start with an Object"); } TwitterEntry result = new TwitterEntry(); // Iterate over object fields: while (jp.nextToken() != JsonToken.END_OBJECT) { String fieldName = jp.getCurrentName(); // Let's move to value jp.nextToken(); if (fieldName.equals("id")) { result.setId(jp.getLongValue()); } else if (fieldName.equals("text")) { result.setText(jp.getText()); } else if (fieldName.equals("fromUserId")) { result.setFromUserId(jp.getIntValue()); } else if (fieldName.equals("toUserId")) { result.setToUserId(jp.getIntValue()); } else if (fieldName.equals("languageCode")) { result.setLanguageCode(jp.getText()); } else { // ignore, or signal error throw new IOException("Unrecognized field '" + fieldName + "'"); } } jp.close(); // important to close both parser and underlying File reader return result; }