gpt4 book ai didi

Java FasterXML JSON 库 : How to parse a nested JSON structure

转载 作者:行者123 更新时间:2023-12-02 04:39:59 25 4
gpt4 key购买 nike

下面是一个 Java 程序,我正在尝试使用 org.fasterxml.jackson.core 和 jackson-databind 库以流方式测试 JSON 处理。

目标是学习如何处理JSON并捕获我想要的信息。目前,我想要完成的任务如下:
1)我在此处发布的 JSON 有大量数据。此 JSON 后面的 Java 程序是我处理此 JSON 的尝试,特别是捕获“part1/myAnalysis/matches”下的 "name": US SSN"元素。以及 "name": MasterCard 信用卡号",这两个元素都属于“part1/myAnalysis/matches”的范围。

好吧,现在我的目标是:我只是希望我的程序能够编译并至少打印出我感兴趣的这两个元素(前面提到的那些)

我的编译尝试产生了以下结果:

Unprocessed property: type
Unprocessed property: incidentTimestamp
Unprocessed property: numOfMatches
Unprocessed property: myReport
Unprocessed property: whatSetItOffEntry
Unprocessed property: seeRestrictedIds
Unprocessed property: status
Unprocessed property: timeStamps
Unprocessed property: count
<小时/>

因此,程序尝试处理的 JSON 如下所示。如果有人可以指出如何使这个程序编译然后打印出我想要的元素。这将是一个很棒的两步流程任务。

{
"type": "ImportantIncidentInfo",
"incidentTimestamp": "2014-05-15T10:09:27.989-05:00",
"numOfMatches": 4,
"myReport": {
"docReports": {
"part1/.": {
"path": [
"unknown"
],
"myAnalysis": {
"matches": [
{
"id": {
"major": 1,
"minor": 0
},
"name": "US SSN",
"position": 13,
"string": " 636-12-4567 "
},
{
"id": {
"major": 3,
"minor": 0
},
"name": "MasterCard Credit Card Number",
"position": 35,
"string": " 5424-1813-6924-3685 "
}
]
},
"cleanedUpData": [
{
"startPosition": 0,
"endPosition": 65,
"frameContent": ""
}
],
"minedMetadata": {
"Content-Encoding": "ISO-8859-1",
"Content-Type": "text/html; charset=iso-8859-1"
},
"deducedMetadata": {
"Content-Type": "text/html; iso-8859-1"
}
},
"part2/.": {
"path": [
"unknown"
],
"patternAnalysis": {
"matches": [
{
"id": {
"major": 1,
"minor": 0
},
"name": "SSN",
"position": 3,
"string": " 636-12-4567\r"
},
{
"id": {
"major": 3,
"minor": 0
},
"name": "MasterCard Credit Card Number",
"position": 18,
"string": "\n5424-1813-6924-3685\r"
}
]
},
"cleanedUpData": [
{
"startPosition": 0,
"endPosition": 44,
"frameContent": ""
}
],
"minedMetadata": {
"Content-Encoding": "windows-1252",
"Content-Type": "text/plain; charset=windows-1252"
},
"deducedMetadata": {
"Content-Type": "text/plain; iso-8859-1"
}
}
}
},
"whatSetItOffEntry": {
"action": "Log",
"component": {
"type": "aComponent",
"components": [
{
"type": "PatternComponent",
"patterns": [
1
],
"not": false
}
],
"not": false
},
"ticketInfo": {
"createIncident": true,
"tags": [],
"seeRestrictedIds": [
{
"type": "userGroup",
"name": "SiteMasters",
"description": "Group for SiteMasters",
"masters": [
"04fb02a2bc0fba"
],
"members": [],
"id": "04fade"
}
]
},
"letmeknowInfo": {
"createNotification": true,
"contactNames": [
"someguy@gmail.com"
]
}
},
"seeRestrictedIds": [
"04fade66c0"
],
"status": "New",
"timeStamps": [
"2014-03-15T10:09:27.989-05:00"
],
"count": 1
}

任务#2
2)为了处理这个JSON,我编写了以下Java程序。

import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.core.*;

import java.io.*;

public class ParseJson {

public static void main(String[] args) {

try{

// TODO Auto-generated method stub
JsonFactory f = new MappingJsonFactory();
//JsonParser jp = f.createJsonParser(new File(args[0]));
JsonParser jp = f.createParser(new File("C:/somepath /in/my/eclipse/project/jsonFormattedModified.json"));


JsonToken current;

current = jp.nextToken();
if (current != JsonToken.START_OBJECT) {
System.out.println("Error: root should be object: quiting.");
return;
}

while (jp.nextToken() != JsonToken.END_OBJECT) {
String fieldName = jp.getCurrentName();
// move from field name to field value
current = jp.nextToken();
if (fieldName.equals("matches")) {
if (current == JsonToken.START_ARRAY) {
// For each of the records in the array
while (jp.nextToken() != JsonToken.END_ARRAY) {
// read the record into a tree model,
// this moves the parsing position to the end of it
JsonNode node = jp.readValueAsTree();
// And now we have random access to everything in the object
System.out.println("Name: " + node.get("name").asText());
System.out.println("POS: " + node.get("pos").asText());
}
} else {
System.out.println("Error: records should be an array: skipping.");
jp.skipChildren();
}
} else {
System.out.println("Unprocessed property: " + fieldName);
jp.skipChildren();
}
}
} catch(IOException ie) {
ie.printStackTrace();

}

}
}
<小时/>

感谢您的帮助。

最佳答案

我建议您使用非常有用的 Google API Gson轻松处理序列化和反序列化。因此,首先,创建以下所有与您的 json 结构匹配的类。

帮助类:

class Helper {
String type;
String incidentTimestamp;
int numOfMatches;
Report myReport;
WhatSetItOffEntry whatSetItOffEntry;
List<String> seeRestrictedIds;
String status;
List<String> timeStamps;
int count;
//getters and setters
}

报告类别:

class Report {
DocsReport docReports;
//getters and setters
}

DocsReport 类:

class DocsReport {
@SerializedName("part1/.")
Part1 part1;
Part2 part2;
//getters and setters
}

第 1 部分类(class):

class Part1 {
List<String> path;
Analysis myAnalysis;
List<CleanedUpData> cleanedUpData;
MinedMetadata minedMetadata;
DeducedMetadata deducedMetadata;
//getters and setters
}

分析类:

class Analysis {
List<Information> matches;
//getters and setters
}

信息类:

class Information {
Identifying id;
String name;
int position;
String string;
//getters and setters
}

识别类别:

class Identifying {
int major;
int minor;
//getters and setters
}

CleanedUpData 类:

class CleanedUpData {
int startPosition;
int endPosition;
String frameContent;
//getters and setters
}

MinedMetadata 类:

class MinedMetadata {
@SerializedName("Content-Encoding")
String contentEncoding;
@SerializedName("Content-Type")
String contentType;
//getters and setters
}

推导元数据类:

class DeducedMetadata {
@SerializedName("Content-Type")
String contentType;
//getters and setters
}

第 2 部分类(class):

class Part2 {
List<String> path;
Analysis patternAnalysis;
CleanedUpData cleanedUpData;
MinedMetadata minedMetadata;
DeducedMetadata deducedMetadata;
//getters and setters
}

WhatSetItOffEntry 类:

class WhatSetItOffEntry {
String action;
Component component;
TicketInfo ticketInfo;
LetmeknowInfo letmeknowInfo;
//getters and setters
}

组件类:

class Component {
String type;
List<ComponentData> components;
Boolean not;
//getters and setters
}

ComponentData 类:

class ComponentData {
String type;
List<Integer> patterns;
Boolean not;
//getters and setters
}

TicketInfo 类:

class TicketInfo {
Boolean createIncident;
List<Object> tags;
List<RestrictedIds> seeRestrictedIds;
//getters and setters
}

RestrictedIds 类:

class RestrictedIds {
String type;
String name;
String description;
List<String> masters;
List<Object> members;
String id;
//getters and setters
}

LetmeknowInfo 类:

class LetmeknowInfo {
Boolean createNotification;
List<String> contactNames;
//getters and setters
}

然后按如下方式获取您的两个名字

Gson gson = new Gson();
Helper data = gson
.fromJson(
new BufferedReader(
new FileReader(
"C:/somepath/in/my/eclipse/project/jsonFormattedModified.json")),
new TypeToken<Helper>() {
}.getType());

String name1 = data.getMyReport().getDocReports().getPart1()
.getMyAnalysis().getMatches().get(0).getName();
String name2 = data.getMyReport().getDocReports().getPart1()
.getMyAnalysis().getMatches().get(1).getName();

System.out.println(name1+"\n"+name2);

输出:

US SSN
MasterCard Credit Card Number

关于Java FasterXML JSON 库 : How to parse a nested JSON structure,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30288878/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com