– Start
除了 ObjectMapper 和 JsonNode 外,Jackson 还提供了更底层 JsonParser 和 JsonGenerator 来读写 JSON。
package shangbo.jackson.demo21;
import java.io.File;
import com.fasterxml.jackson.core.JsonEncoding;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonGenerator;
public class App {
public static void main(String[] args) throws Exception {
// 实例化 JsonFactory 和 JsonParser 对象
JsonFactory factory = new JsonFactory();
JsonGenerator gernerator = factory.createGenerator(new File("D:\\0_Shangbo\\Dev\\people.json"), JsonEncoding.UTF8);
// 生成 json
gernerator.writeStartObject();
gernerator.writeStringField("firstname", "Bo");
gernerator.writeStringField("lasttname", "Shang");
gernerator.writeNumberField("age", 30);
gernerator.writeEndObject();
gernerator.close();
}
}
package shangbo.jackson.demo20;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;
public class App {
public static void main(String[] args) throws Exception {
// json 消息
String json = "{\"firstname\":\"Bo\",\"lastname\":\"Shang\",\"age\":30}";
// 实例化 JsonFactory 和 JsonParser 对象
JsonFactory factory = new JsonFactory();
JsonParser parser = factory.createParser(json);
// 解析 json
while(!parser.isClosed()) {
JsonToken jsonToken = parser.nextToken();
if(JsonToken.FIELD_NAME.equals(jsonToken)) {
String fieldName = parser.getCurrentName();
jsonToken = parser.nextToken();
System.out.println(fieldName + ":" + parser.getValueAsString());
}
}
}
}
– 更多参见:Jackson 精萃
– 声 明:转载请注明出处
– Last Updated on 2019-05-26
– Written by ShangBo on 2019-05-26
– End