如何在Java中使用JsonParserSequence顺序合并两个JSON字符串?
JsonParserSequence 是一个 可被用于创建包含两个子解析器放置在解析器辅助类 特定序列。我们可以创建一个使用序列静态 方法)createFlattened( 中的JsonParserSequence 类。
语法
public static JsonParserSequence createFlattened(JsonParser first, JsonParser second)
示例
import java.io.*; import com.fasterxml.jackson.core.*; import com.fasterxml.jackson.core.util.*; public class JsonParserSequenceTest { public static void main(String[] args) throws JsonParseException, IOException { String jsonString1 = "{\"id\":\"101\", \"name\":\"Ravi Chandra\", \"address\":\"Pune\"}"; String jsonString2 = "{\"id\":\"102\", \"name\":\"Raja Ramesh\", \"address\":\"Hyderabad\", \"contacts\":[{\"mobile\":\"9959984805\", \"home\":\"7702144400\"}]}"; JsonFactory jsonFactory = new JsonFactory(); JsonParser jsonParser1 = jsonFactory.createParser(jsonString1); JsonParser jsonParser2 = jsonFactory.createParser(jsonString2); JsonParserSequence jsonParserSequence = JsonParserSequence.createFlattened(jsonParser1, jsonParser2); JsonToken jsonToken = jsonParserSequence.nextToken(); while(jsonToken != null) { switch(jsonToken) { case FIELD_NAME: System.out.println("Key field: " + jsonParserSequence.getText()); break; case VALUE_FALSE: case VALUE_NULL: case VALUE_NUMBER_FLOAT: case VALUE_NUMBER_INT: case VALUE_STRING: case VALUE_TRUE: System.out.println("Key value: " + jsonParserSequence.getText()); break; } jsonToken = jsonParserSequence.nextToken(); } jsonParserSequence.close(); } }
输出结果
Key field: id Key value: 101 Key field: name Key value: Ravi Chandra Key field: address Key value: Pune Key field: id Key value: 102 Key field: name Key value: Raja Ramesh Key field: address Key value: Hyderabad Key field: contacts Key field: mobile Key value: 9959984805 Key field: home Key value: 7702144400