我的目标是阅读非结构化JSON文件并将该文件加载到数据库中:
基本上我有下表:
drop table stg_json_structure;
create table stg_json_structure
(
id bigint not null primary key auto_increment,
meta_data varchar(500),
meta_value longtext,
parent_id bigint,
type varchar(100),
array_index int,
created datetime,
foreign key (parent_id) references stg_json_structure(id)
)
其中:
id - PK
meta_data - Json key
meta_data - Json value
array_index - if it's Array type when put here array index
created - timestamp of inserted record
所以parent_id应该指向json文件中父键的ID。
我编写以下Java代码来读取递归的Json文件。
// 1
public static void undefinedJson() {
ObjectMapper mapper = new ObjectMapper();
try {
JsonParser parser = mapper.getJsonFactory().createJsonParser(new File("/tmp/test_json.txt"));
while (parser.nextToken() != null) {
System.out.println(parser.getCurrentToken());
if (JsonToken.START_ARRAY.equals(parser.getCurrentToken())) {
JsonNode node = parser.readValueAsTree();
readJsonArrayNode(node);
}
else if (JsonToken.START_OBJECT.equals(parser.getCurrentToken())) {
JsonNode node = parser.readValueAsTree();
readJsonObjectNode(node);
}
}
}
catch(Exception ex) {
ex.printStackTrace();
}
}
// 2
public static void readJsonArrayNode(JsonNode node) {
if (node.isArray()) {
for (int i=0;i<node.size();i++) {
System.out.println("array index="+i);
JsonNode child = node.get(i);
if (child.isObject()) {
readJsonObjectNode(child);
}
else if (child.isArray()) {
readJsonArrayNode(child);
}
else {
System.out.println(child);
}
}
}
}
// 3
public static void readJsonObjectNode(JsonNode node) {
if (node.isObject()) {
Iterator<Map.Entry<String,JsonNode>> i=node.getFields();
while (i.hasNext()) {
Map.Entry<String,JsonNode> jsonNode=i.next();
String key = jsonNode.getKey();
JsonNode temp = jsonNode.getValue();
if (temp.isArray()) {
System.out.print(key+"=");
System.out.println(temp);
readJsonArrayNode(temp);
}
else if (temp.isObject()) {
System.out.println();
System.out.println("ObjectNode");
System.out.print(key+"=");
System.out.println(temp);
readJsonObjectNode(temp);
}
else {
if (temp.isValueNode()) {
System.out.println();
System.out.println("ValueNode");
System.out.print(key+"=");
System.out.println(temp);
}
}
}
}
}
//4
public static void main(String[] args) {
undefinedJson();
}
现在我的问题是如何获得子节点的parent_id?检查上表我需要将其插入数据库。