我们必须解析类似于下面的 json 结构。
project {
header {
}
pool {
}
cmp {
name = "";
id = "";
desc = "";
cmp [
{
name = "";
id = "";
desc = "";
}
{
name = "";
id = "";
desc = "";
}
{
name = "";
id = "";
desc = "";
cmp [
{
name = "";
id = "";
desc = "";
}
}
}
}
问题是,cmp 元素无限存在于 json 中(而且它也是递归的)。 cmp 元素包含许多除 name、id 和 desc 之外的属性。但我们只需要从 jSON 中提取 name、id 和 desc。
我可以使用 com.json.parsers.JSONParser 解析 JSON 字符串。但是将解析的 JSON 填充到模型类/bean 类是行不通的。这可能是一个简单的逻辑。但是我不能。请帮助...
json 文件是作为一个建模软件的输出生成的。
我想用 java 解析这个。有人可以帮我解析吗?
希望我已经正确解释了这个问题。您的帮助将对我们有所帮助。
最佳答案
您可以使用 Jackson 执行此操作,只需使用消息中可能存在或不存在的所有字段创建您的对象。消息中不存在的所有字段在生成的对象中都将以 null(或原语的默认值)结束。
只需让对象包含其自身的副本,这将处理递归
@XmlRootElement
public class Foo {
Foo recursiveFoo; // will be null or another instance of Foo
int intData; // Will be 0 or an integer value
String strData; // Will be null or a String value
// Getters and setters here
}
关于java - 用于递归结构的json解析器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20635220/