【问题标题】:gson parsing nested json objectsgson解析嵌套的json对象
【发布时间】:2013-03-16 17:11:13
【问题描述】:

我正在尝试将 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 }
    ]
}

我需要忽略 cmets 并转换规则。这是我试图为规则 java 对象定义的 java 类型:

// Arraylist < Map < elementname, Map < name, value >  > >
ArrayList< Map<String, Map<String, String>  > > rules;

有没有简单的方法用 gson 做到这一点?

【问题讨论】:

    标签: java json collections gson


    【解决方案1】:

    使用这个

    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);
    

    【讨论】:

    • 你能解释一下吗? gson.fromJson 中的类型规范是否会自动从 json 中查找匹配类型?我试图了解如何跳过“评论”对象。
    • 类型规范(新的 TypeToken 等)帮助 Gson 序列化复杂类型(即,当键从对象派生时,对象列表甚至映射,尽管在您的情况下,您的映射使用纯字符串)。我想您可以创建一个适合您的 JSON 字符串的自定义类型,对其进行反序列化(包括 cmets !)并忽略它们
    【解决方案2】:

    您可以声明特定的类:

    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());
          }
       }
    }
    

    这里是 long 版本:

    import java.io.BufferedReader;
    import java.io.FileReader;
    import java.io.IOException;
    
    import com.google.gson.Gson;
    
    class Rule {
       String element;
       boolean skip;
    
       @Override public String toString() {
          StringBuilder sb = new StringBuilder();
          sb.append( '\t' );
          sb.append( element );
          sb.append( " ==> " );
          sb.append( skip );
          sb.append( '\n' );
          return sb.toString();
       }   
    }
    class ElementParser {
       String[] comment;
       Rule[]    rules;
    
       @Override public String toString() {
          StringBuilder sb = new StringBuilder();
          sb.append( "Comment:\n" );
          for( String c : comment ) {
             sb.append( '\t' );
             sb.append( c );
             sb.append( '\n' );
          }
          sb.append( "Rules:\n" );
          for( Rule r : rules ) {
             sb.append( r.toString());
          }
          return sb.toString();
       }
    }
    
    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
    

    【讨论】:

    【解决方案3】:

    你也可以试试这个..

    用于保存规则和 cmets 的数据类

    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;
        }
    
    }
    

    保持元素和跳过的规则类 公共类规则 {

        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;
        }
    
    }
    

    最后,您可以使用类似的方法将 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());
            }
        }
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多