Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/variables/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java gson解析嵌套的json对象_Java_Json_Collections_Gson - Fatal编程技术网

Java gson解析嵌套的json对象

Java gson解析嵌套的json对象,java,json,collections,gson,Java,Json,Collections,Gson,我试图将json字符串解析为java对象。目前,代码正在手动读取文件并生成java对象。但是,我希望将实现带到gson 以下是我从web服务调用中收到的json: { "comment": [ "This file is used to define the behavior for the elements parsed.", "Each entry in the file will have the format of element:name, skip:b

我试图将json字符串解析为java对象。目前,代码正在手动读取文件并生成java对象。但是,我希望将实现带到gson

以下是我从web服务调用中收到的json:

{ "comment": [
        "This file is used to define the behavior for the elements parsed.",
        "Each entry in the file will have the format of element:name, skip:bool",
        "If SkipFlag is true, it means that element need not be processed.",
        "Convention used for elements and rule names is camelCase"
    ],
    "rules": [ { "element": "html", "skip": true },
               { "element": "head", "skip": true },
               { "element": "head", "skip": true },
               { "element": "body", "skip": true }
    ]
}
我需要忽略注释并转换规则。以下是我试图为java对象规则定义的java类型:

// Arraylist < Map < elementname, Map < name, value >  > >
ArrayList< Map<String, Map<String, String>  > > rules;
//Arraylist>
ArrayList规则;
使用gson有没有一种简单的方法可以做到这一点

GsonBuilder builder = new GsonBuilder();    
Gson gson = builder.enableComplexMapKeySerialization().create(); 
Type type = new TypeToken<ArrayList< Map<String, ArrayList<Map<String, String> > > >>() {}.getType();
ArrayList< Map<String, ArrayList<Map<String, String> > > > obj = gson.fromJson(str, type);
GsonBuilder=newgsonbuilder();
Gson Gson=builder.enableComplexMapKeySerialization().create();
Type Type=newTypeToken>(){}.getType();
ArrayListobj=gson.fromJson(str,type);

您可以声明特定的类:

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

import com.google.gson.Gson;

class Rule {
   String  element;
   boolean skip;
}

class ElementParser {
   String[] comment;
   Rule[]   rules;
}

public class JSonDecoder {
   public static void main( String[] args ) throws IOException {
      try( BufferedReader reader =
              new BufferedReader( new FileReader( "Skip.json" ))) {
         System.out.println( 
            new Gson().fromJson( reader, ElementParser.class ).toString());
      }
   }
}
以下是长版本:

结果:

Comment:
    This file is used to define the behavior for the elements parsed.
    Each entry in the file will have the format of element:name, skip:bool
    If SkipFlag is true, it means that element need not be processed.
    Convention used for elements and rule names is camelCase
Rules:
    html ==> true
    head ==> true
    head ==> true
    body ==> true
你也可以试试这个

用于保存规则和注释的数据类

import java.util.List;

public class Data {

    private List<String> comments;
    private List<Rule> rules;

    public Data() {}

    public List<String> getComments() {
        return comments;
    }

    public void setComments(List<String> comments) {
        this.comments = comments;
    }

    public List<Rule> getRules() {
        return rules;
    }

    public void setRules(List<Rule> rules) {
        this.rules = rules;
    }

}
最后,您可以使用类似的方法将json中的规则转换为java:

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.List;

import com.google.gson.Gson;

public class GsonTest {

    public static void main(String[] args) throws FileNotFoundException {
        BufferedReader bufferedReader = new BufferedReader(new FileReader("C:/Users/JESNAMOL/Desktop/json.txt"));//i have kept  your json string in a file for demonstration
        Gson gson = new Gson();
        Data data = gson.fromJson(bufferedReader, Data.class);
        List<Rule> rules = data.getRules();

        for (Rule rule : rules) {
            System.out.println("element: " + rule.getElement());
            System.out.println("skip: " + rule.isSkip());
        }
    }

}
导入java.io.BufferedReader;
导入java.io.FileNotFoundException;
导入java.io.FileReader;
导入java.util.List;
导入com.google.gson.gson;
公共类GsonTest{
公共静态void main(字符串[]args)引发FileNotFoundException{
BufferedReader BufferedReader=new BufferedReader(new FileReader(“C:/Users/JESNAMOL/Desktop/json.txt”);//我将您的json字符串保存在一个文件中以供演示
Gson Gson=新的Gson();
Data=gson.fromJson(bufferedReader,Data.class);
列表规则=data.getRules();
for(规则:规则){
System.out.println(“元素:+rule.getElement());
System.out.println(“跳过:+rule.isSkip());
}
}
}

你能解释一下吗?
gson.fromJson
中的类型规范是否会自动从json中查找匹配的类型?我试图理解“comment”对象是如何被跳过的。类型规范(新的TypeToken等)有助于Gson序列化复杂类型(即,当键从对象派生时,对象列表甚至映射,尽管在您的情况下,映射使用纯字符串)。我想您可以创建一个适合您的JSON字符串的自定义类型,对它进行反序列化(包括注释!),然后简单地忽略它们。规则是“每个文件只有一个公共类”。
    private String element;
    private boolean skip;

    public Rule() {}

    public String getElement() {
        return element;
    }

    public void setElement(String element) {
        this.element = element;
    }

    public boolean isSkip() {
        return skip;
    }

    public void setSkip(boolean skip) {
        this.skip = skip;
    }

}
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.List;

import com.google.gson.Gson;

public class GsonTest {

    public static void main(String[] args) throws FileNotFoundException {
        BufferedReader bufferedReader = new BufferedReader(new FileReader("C:/Users/JESNAMOL/Desktop/json.txt"));//i have kept  your json string in a file for demonstration
        Gson gson = new Gson();
        Data data = gson.fromJson(bufferedReader, Data.class);
        List<Rule> rules = data.getRules();

        for (Rule rule : rules) {
            System.out.println("element: " + rule.getElement());
            System.out.println("skip: " + rule.isSkip());
        }
    }

}