Java 使用Jackson解析Json文件

Java 使用Jackson解析Json文件,java,json,parsing,jackson,pojo,Java,Json,Parsing,Jackson,Pojo,我的POJO是: { "TestSuite":{ "TestSuiteInfo":{ "-description":"parse" }, "TestCase":[ { "TestCaseData":{ "-sequence":"sequential", "-testNumber":"2", "-testCa

我的POJO是:

{
   "TestSuite":{
      "TestSuiteInfo":{
         "-description":"parse"
      },
      "TestCase":[
         {
            "TestCaseData":{
               "-sequence":"sequential",
               "-testNumber":"2",
               "-testCaseFile":"testcase\\Web\\Ab.xml"
            }
         },
         {
            "TestCaseData":{
               "-sequence":"sequential",
               "-testNumber":"3",
               "-testCaseFile":"testcase\\Web\\BC.xml"
            }
         }
      ]
   }
}
公共类测试套件{
私有TestSuiteInfo TestSuiteInfo;
私人测试用例列表;
公共TestSuiteInfo getTestSuiteInfo(){
返回testSuiteInfo;
}
public void setTestSuiteInfo(TestSuiteInfo TestSuiteInfo){
this.testSuiteInfo=testSuiteInfo;
}
公共测试用例getListOfTestCases(){
返回测试用例列表;
}
公共无效setListOfTestCases(TestCase listOfTestCases){
this.listOfTestCases=listOfTestCases;
}
}
公共类TestSuiteInfo{
私有字符串描述;
公共字符串getDescription(){
返回说明;
}
公共void集合描述(字符串描述){
this.description=描述;
}
}
导入java.util.Iterator;
导入java.util.List;
公共类测试用例{
私有列表测试用例数据;
公共列表getTestCaseData(){
返回testCaseData;
}
公共void setTestCaseData(列出testCaseData){
this.testCaseData=testCaseData;
}
}
公共类TestCaseData{
私有字符串序列;
私有int testNumber;
私有字符串testCaseFile;
公共字符串getSequence(){
返回序列;
}
公共void集合序列(字符串序列){
这个序列=序列;
}
public int getTestNumber(){
返回testNumber;
}
公共void setTestNumber(int testNumber){
this.testNumber=testNumber;
}
公共字符串getTestCaseFile(){
返回testCaseFile;
}
公共void setTestCaseFile(字符串testCaseFile){
this.testCaseFile=testCaseFile;
}
}
我以前没有使用过Jackson,如果有人能帮我解析文件并获取对象,我将不胜感激。
过去两天我一直在尝试解析这个,但没有成功

通常要使用Jackson库解析JSON,您会使用如下
ObjectMapper
类:

public class TestSuite {    

    private TestSuiteInfo testSuiteInfo;
    private TestCase listOfTestCases;

    public TestSuiteInfo getTestSuiteInfo() {   
        return testSuiteInfo;
    }

    public void setTestSuiteInfo(TestSuiteInfo testSuiteInfo) {
        this.testSuiteInfo = testSuiteInfo;
    }

    public TestCase getListOfTestCases() {
        return listOfTestCases;
    }

    public void setListOfTestCases(TestCase listOfTestCases) {
        this.listOfTestCases = listOfTestCases;
    }
}


public class TestSuiteInfo {

    private String description;

    public String getDescription() {
        return description;
    }
    public void setDescription(String description) {
        this.description = description;
    }
}


import java.util.Iterator;
import java.util.List;

public class TestCase {

    private List<TestCaseData> testCaseData;

    public List<TestCaseData> getTestCaseData() {
        return testCaseData;
    }

    public void setTestCaseData(List<TestCaseData> testCaseData) {
        this.testCaseData = testCaseData;
    }
}


public class TestCaseData {

    private String sequence;
    private int testNumber;
    private String testCaseFile;

    public String getSequence() {   
        return sequence;
    }

    public void setSequence(String sequence) {
        this.sequence = sequence;
    }

    public int getTestNumber() {
        return testNumber;
    }

    public void setTestNumber(int testNumber) {
        this.testNumber = testNumber;
    }

    public String getTestCaseFile() {
        return testCaseFile;
    }

    public void setTestCaseFile(String testCaseFile) {
        this.testCaseFile = testCaseFile;
    }
}
public static void main(final String[] args) {
    final String json = "some JSON string";
    final ObjectMapper mapper = new ObjectMapper();
    final TestSuite readValue = mapper.readValue(json, TestSuite.class);
    //Then some code that uses the readValue.
    //Keep in mind that the mapper.readValue() method does throw some exceptions
    //So you'll need to handle those too.    
}
然而,我编写了一个快速测试类来检查JSON的解析,并遇到了一些问题

基本上,JSON的设计和域的设计是不匹配的。因此,您可以更改JSON,也可以更改域对象

更改JSON以适应域

  • 带有“-”的属性名在jackson中无法很好地解析,因此需要删除它们
  • 将类名放在每个对象之前不会有任何帮助。Jackson希望这些是属性,因此需要删除类名或用属性名替换类名
  • 必须提供域对象中的属性名,以便jackson解析它们。你不能只说这里有一个对象,然后开始一个列表,列表必须有一个属性名/
  • 在我调整了JSON中的这些内容之后,我让它用提供的域对象进行解析。我最终得到的JSON如下所示:

    public class TestSuite {    
    
        private TestSuiteInfo testSuiteInfo;
        private TestCase listOfTestCases;
    
        public TestSuiteInfo getTestSuiteInfo() {   
            return testSuiteInfo;
        }
    
        public void setTestSuiteInfo(TestSuiteInfo testSuiteInfo) {
            this.testSuiteInfo = testSuiteInfo;
        }
    
        public TestCase getListOfTestCases() {
            return listOfTestCases;
        }
    
        public void setListOfTestCases(TestCase listOfTestCases) {
            this.listOfTestCases = listOfTestCases;
        }
    }
    
    
    public class TestSuiteInfo {
    
        private String description;
    
        public String getDescription() {
            return description;
        }
        public void setDescription(String description) {
            this.description = description;
        }
    }
    
    
    import java.util.Iterator;
    import java.util.List;
    
    public class TestCase {
    
        private List<TestCaseData> testCaseData;
    
        public List<TestCaseData> getTestCaseData() {
            return testCaseData;
        }
    
        public void setTestCaseData(List<TestCaseData> testCaseData) {
            this.testCaseData = testCaseData;
        }
    }
    
    
    public class TestCaseData {
    
        private String sequence;
        private int testNumber;
        private String testCaseFile;
    
        public String getSequence() {   
            return sequence;
        }
    
        public void setSequence(String sequence) {
            this.sequence = sequence;
        }
    
        public int getTestNumber() {
            return testNumber;
        }
    
        public void setTestNumber(int testNumber) {
            this.testNumber = testNumber;
        }
    
        public String getTestCaseFile() {
            return testCaseFile;
        }
    
        public void setTestCaseFile(String testCaseFile) {
            this.testCaseFile = testCaseFile;
        }
    }
    
    public static void main(final String[] args) {
        final String json = "some JSON string";
        final ObjectMapper mapper = new ObjectMapper();
        final TestSuite readValue = mapper.readValue(json, TestSuite.class);
        //Then some code that uses the readValue.
        //Keep in mind that the mapper.readValue() method does throw some exceptions
        //So you'll need to handle those too.    
    }
    
    下面是我的测试方法,它可以解析上面修改过的JSON(请忽略所有转义字符)

    更改域以适应JSON

    首先,主要问题是将类名作为属性标识符。这使得以通常的方式使用此JSON非常困难。我不得不添加几个包装类来绕过JSON中的类名

    • 我添加了一个
      OverallWrapper
      类,该类具有
      TestSuite
      属性,以适应JSON中的TestSuite类名

    • 我还添加了一个
      TestCaseDataWrapper
      类,以满足JSON中列表中的TestCaseData类名

    • 我一起删除了TestCase类,因为它只是其他一个类的一个属性

    • 然后为了使属性名与对象匹配,我使用了
      @JsonProperty
      注释

    下面是修改后的类,以及工作和解析JSON的最终解析器测试方法。(同样,请原谅JSON字符串中的所有转义字符)

    import org.codehaus.jackson.annotate.JsonProperty;
    公共类整体包装器{
    私人测试套件;
    @JsonProperty(“TestSuite”)
    公共测试套件getTestSuite(){
    返回此.testSuite;
    }                                                      
    公共无效设置测试套件(最终测试套件测试套件){
    this.testSuite=testSuite;
    }                                                      
    }
    导入java.util.List;
    导入org.codehaus.jackson.annotate.JsonProperty;
    公共类测试套件{
    私有TestSuiteInfo TestSuiteInfo;
    私有列表测试用例数据;
    @JsonProperty(“测试用例”)
    公共列表getTestCaseData(){
    返回this.testCaseData;
    }                                                                           
    public void setTestCaseData(最终列表testCaseData){
    this.testCaseData=testCaseData;
    }                                                                           
    @JsonProperty(“TestSuiteInfo”)
    公共TestSuiteInfo getTestSuiteInfo(){
    返回this.testSuiteInfo;
    
    import org.codehaus.jackson.annotate.JsonProperty;         
    
    public class OverallWrapper {                              
    
        private TestSuite testSuite;                           
    
        @JsonProperty("TestSuite")                             
        public TestSuite getTestSuite() {                      
            return this.testSuite;                             
        }                                                      
    
        public void setTestSuite(final TestSuite testSuite) {  
            this.testSuite = testSuite;                        
        }                                                      
    }
    
    
    
    import java.util.List;                                                                                                                                  
    import org.codehaus.jackson.annotate.JsonProperty;                              
    
    public class TestSuite {                                                        
    
        private TestSuiteInfo testSuiteInfo;                                        
    
        private List<TestCaseDataWrapper> testCaseData;                             
    
        @JsonProperty("TestCase")                                                   
        public List<TestCaseDataWrapper> getTestCaseData() {                        
            return this.testCaseData;                                               
        }                                                                           
    
        public void setTestCaseData(final List<TestCaseDataWrapper> testCaseData) { 
            this.testCaseData = testCaseData;                                       
        }                                                                           
    
        @JsonProperty("TestSuiteInfo")                                              
        public TestSuiteInfo getTestSuiteInfo() {                                   
            return this.testSuiteInfo;                                              
        }                                                                           
    
        public void setTestSuiteInfo(final TestSuiteInfo testSuiteInfo) {           
            this.testSuiteInfo = testSuiteInfo;                                     
        }                                                                                                                                                   
    }          
    
    
    
    import org.codehaus.jackson.annotate.JsonProperty;          
    
    public class TestSuiteInfo {                                
    
        private String description;                             
    
        @JsonProperty("-description")                           
        public String getDescription() {                        
            return this.description;                            
        }                                                       
        public void setDescription(final String description) {  
            this.description = description;                     
        }                                                       
    }                                                                                                                                
    
    
    
    import org.codehaus.jackson.annotate.JsonProperty;                  
    
    public class TestCaseDataWrapper {                                  
    
        @JsonProperty("TestCaseData")                                   
        private TestCaseData testcaseData;                              
    
        public TestCaseData getTestcaseData() {                         
            return this.testcaseData;                                   
        }                                                               
    
        public void setTestcaseData(final TestCaseData testcaseData) {  
            this.testcaseData = testcaseData;                           
        }                                                               
    }       
    
    
    
    import org.codehaus.jackson.annotate.JsonProperty;             
    
    public class TestCaseData {                                    
    
        private String sequence;                                   
        private int testNumber;                                    
        private String testCaseFile;                               
    
        @JsonProperty("-sequence")                                 
        public String getSequence() {                              
            return this.sequence;                                  
        }                                                          
    
        public void setSequence(final String sequence) {           
            this.sequence = sequence;                              
        }                                                          
    
        @JsonProperty("-testNumber")                               
        public int getTestNumber() {                               
            return this.testNumber;                                
        }                                                          
    
        public void setTestNumber(final int testNumber) {          
            this.testNumber = testNumber;                          
        }                                                          
    
        @JsonProperty("-testCaseFile")                             
        public String getTestCaseFile() {                          
            return this.testCaseFile;                              
        }                                                          
    
        public void setTestCaseFile(final String testCaseFile) {   
            this.testCaseFile = testCaseFile;                      
        }                                                          
    }                                                              
    
    
    
    public static void main(final String[] args) {
    
        final String json = "{\"TestSuite\":{\"TestSuiteInfo\":{\"-description\":\"parse\"},\"TestCase\":[" +
                "{\"TestCaseData\":{\"-sequence\":\"sequential\",\"-testNumber\":\"2\",\"-testCaseFile\":\"testcase\\\\Web\\\\Ab.xml\"}}," +
                "{\"TestCaseData\":{\"-sequence\":\"sequential\",\"-testNumber\":\"3\",\"-testCaseFile\":\"testcase\\\\Web\\\\BC.xml\"}}" +
                "]}}";
    
        final ObjectMapper mapper = new ObjectMapper();
    
        try {
            final OverallWrapper readValue = mapper.readValue(json, OverallWrapper.class);
    
            System.out.println(readValue.getTestSuite());
        }
        catch (final Exception e) {
            e.printStackTrace();
        }
    }
    
    outerloop: while (jp.nextToken() != JsonToken.END_OBJECT) {
      //...nested loops here
      break outerloop;
      //...closing loops
    }
    
    import org.codehaus.jackson.map.*;
    import org.codehaus.jackson.*;
    
    import java.io.File;
    
    public class ParseJsonSample {
      public static void main(String[] args) throws Exception {
        JsonFactory f = new MappingJsonFactory();
        JsonParser jp = f.createJsonParser(new File(args[0]));
    
        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("records")) {
            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("field1: " + node.get("field1").getValueAsText());
                System.out.println("field2: " + node.get("field2").getValueAsText());
              }
            } else {
              System.out.println("Error: records should be an array: skipping.");
              jp.skipChildren();
            }
          } else {
            System.out.println("Unprocessed property: " + fieldName);
            jp.skipChildren();
          }
        }                
      }
    }