使用杰克逊将xml转换为Java对象

时间:2018-09-03 17:23:47

标签: java json jackson

我想使用Jackson库将XML转换为JSON。我已经尝试过下面的代码使用杰克逊来获得Json如下,但我不能。如果我尝试使用json,我可以,但是我想知道如何使用Jackson库。

@RequestMapping(value="/convertXMLtoJson",method=RequestMethod.POST,consumes = MediaType.APPLICATION_XML_VALUE)
        public Map<String,Object> convertXMLtoJson(@RequestBody String strXMLData) {
            Map<String,Object> objresponseMessage = null;
            ObjectMapper objObjectMapper = new ObjectMapper();
            Employee objEmployee = null;
            try {
                JSONObject obj = XML.toJSONObject(strXMLData);
                ObjectMapper objectMapper = new XmlMapper();
                objEmployee = objectMapper.readValue(strXMLData, Employee.class);
            objEmployeeService.save(objEmployee);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return objresponseMessage;
        }

com.fasterxml.jackson.databind.exc.MismatchedInputException:无法从VALUE_STRING令牌中反序列化java.util.HashSet的实例  在[来源:(StringReader);行:5,列:15](通过参考链:com.example.springboot.bean.Employee [“ Skills”])

<EmployeeDetail>
   <FirstName>A</FirstName>
   <LastName>Z</LastName>
   <Age>20</Age>
   <Skills>Java</Skills>
   <Skills>J2EE</Skills>
   <Skills>MSSQl</Skills>
   <Skills>JAVA</Skills>
   <TotalExperience>4</TotalExperience>
   <JobDetails>
      <CompanyName>1</CompanyName>
      <Experience>1.5</Experience>
      <Technologies>Java</Technologies>
      <Technologies>WebServices</Technologies>
      <Technologies>MSSQL</Technologies>
      <Technologies>J2EE</Technologies>
      <Location>India</Location>
   </JobDetails>
   <JobDetails>
      <CompanyName>2</CompanyName>
      <Experience>2.5</Experience>
      <Technologies>Java</Technologies>
      <Technologies>J2EE</Technologies>
      <Technologies>MySQL</Technologies>
      <Technologies>Spring</Technologies>
      <Location>India</Location>
   </JobDetails>
</EmployeeDetail>

期望Json为(接受输出)

{
    "EmployeeDetail": {
        "FirstName": "A",
        "LastName": "Z",
        "Age": "20",
        "Skills": [
            "Java",
            "J2EE",
            "MSSQl",
            "JAVA"
        ],
        "TotalExperience": "4",
        "JobDetails": [
            {
                "CompanyName": "1",
                "Experience": "1.5",
                "Technologies": [
                    "Java",
                    "WebServices",
                    "MSSQL",
                    "J2EE"
                ],
                "Location": "India"
            },
            {
                "CompanyName": "2",
                "Experience": "2.5",
                "Technologies": [
                    "Java",
                    "J2EE",
                    "MySQL",
                    "Spring"
                ],
                "Location": "India"
            }
        ]
    }
}

任何人都可以帮助我了解使用Jackson库的情况

import java.io.Serializable;
import java.util.List;
import java.util.Set;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlElementWrapper;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement;

@Document
@JacksonXmlRootElement(localName="EmployeeDetail")
public class Employee implements Serializable {

    @Id
    private String userId;

    @JacksonXmlProperty(localName="FirstName")
    @JsonProperty("FirstName")
    private String firstName;

    @JacksonXmlProperty(localName="LastName")
    @JsonProperty("LastName")
    private String lastName;

    @JacksonXmlProperty(localName="Age")
    @JsonProperty("Age")
    private Integer age;

    @JacksonXmlElementWrapper(localName="Skills")
    @JsonProperty("Skills")
    private Set<String> skills;

    @JacksonXmlProperty(localName="JobDetails")
    @JsonProperty("JobDetails")
    private List<JobDetails> jobDetails;

    public String getUserId() {
        return userId;
    }

    public void setUserId(String userId) {
        this.userId = userId;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public List<JobDetails> getJobDetails() {
        return jobDetails;
    }

    public void setJobDetails(List<JobDetails> jobDetails) {
        this.jobDetails = jobDetails;
    }

    public Set<String> getSkills() {
        return skills;
    }

    public void setSkills(Set<String> skills) {
        this.skills = skills;
    }

}

import java.util.Set;    
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlElementWrapper;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement;

@JacksonXmlRootElement(localName="JobDetails")
public class JobDetails {

    JobDetails(String str) {

    }

    @JacksonXmlProperty(localName="CompanyName")
    @JsonProperty("CompanyName")
    private String companyName;

    @JacksonXmlProperty(localName="Experience")
    @JsonProperty("Experience")
    private Integer experience;

    @JacksonXmlProperty(localName="Location")
    @JsonProperty("Location")
    private String location;

    @JacksonXmlElementWrapper(localName="Technologies")
    @JsonProperty("Technologies")
    private Set<String> technologies;

    public String getCompanyName() {
        return companyName;
    }

    public void setCompanyName(String companyName) {
        this.companyName = companyName;
    }

    public Integer getExperience() {
        return experience;
    }

    public void setExperience(Integer experience) {
        this.experience = experience;
    }

    public String getLocation() {
        return location;
    }

    public void setLocation(String location) {
        this.location = location;
    }

    public Set<String> getTechnologies() {
        return technologies;
    }

    public void setTechnologies(Set<String> technologies) {
        this.technologies = technologies;
    }

}

2 个答案:

答案 0 :(得分:0)

知道Employee类的实现可能很有用。

您用skills注释的@JsonProperty("Skills")字段大写吗?

@JsonProperty("Skills")
private Set<String> skills;

区分大小写应该很重要。

答案 1 :(得分:0)

更改您的xml输入数据,无论它们在tag中作为集合组是什么,并在java文件的注释“ localName”中修改@JacksonXmlElementWrapper。这是做什么的。

    <EmployeeDetail>
       <FirstName>A</FirstName>
       <LastName>Z</LastName>
       <Age>20</Age>
        <skillset>
       <Skills>Java</Skills>
       <Skills>J2EE</Skills>
       <Skills>MSSQl</Skills>
       <Skills>JAVA</Skills>
       </skillset>
       <TotalExperience>4</TotalExperience>
<jobs>
       <JobDetails>
          <CompanyName>1</CompanyName>
          <Experience>1.5</Experience>
<technologyList>
          <Technologies>Java</Technologies>
          <Technologies>WebServices</Technologies>
          <Technologies>MSSQL</Technologies>
          <Technologies>J2EE</Technologies>
</technologyList>
          <Location>India</Location>
       </JobDetails>
       <JobDetails>
          <CompanyName>2</CompanyName>
          <Experience>2.5</Experience>
<technologyList>
          <Technologies>Java</Technologies>
          <Technologies>J2EE</Technologies>
          <Technologies>MySQL</Technologies>
          <Technologies>Spring</Technologies>
</technologyList>
          <Location>India</Location>
       </JobDetails>
</jobs>
    </EmployeeDetail>

现在修改Employee.java类以遵循

    import java.util.List;
    import java.util.Set;
    import org.springframework.data.annotation.Id;
    import org.springframework.data.mongodb.core.mapping.Document;
    import com.fasterxml.jackson.annotation.JsonProperty;
    import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlElementWrapper;
    import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;
    import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement;

    @Document
    @JacksonXmlRootElement(localName="EmployeeDetail")
    public class Employee implements Serializable {

        @Id
        private String userId;

        @JacksonXmlProperty(localName="FirstName")
        @JsonProperty("FirstName")
        private String firstName;

        @JacksonXmlProperty(localName="LastName")
        @JsonProperty("LastName")
        private String lastName;

        @JacksonXmlProperty(localName="Age")
        @JsonProperty("Age")
        private Integer age;

        @JacksonXmlElementWrapper(localName="skillset")
        @JsonProperty("Skills")
        private Set<String> skills;

        @JacksonXmlElementWrapper(localName="jobs")
        @JsonProperty("JobDetails")
        private List<JobDetails> jobDetails;

        @JacksonXmlProperty(localName="TotalExperience")
        @JsonProperty("totalExperience")
        private Integer totalExperience;

        public String getUserId() {
            return userId;
        }

        public void setUserId(String userId) {
            this.userId = userId;
        }

        public Integer getAge() {
            return age;
        }

        public void setAge(Integer age) {
            this.age = age;
        }

        public String getLastName() {
            return lastName;
        }

        public void setLastName(String lastName) {
            this.lastName = lastName;
        }

        public String getFirstName() {
            return firstName;
        }

        public void setFirstName(String firstName) {
            this.firstName = firstName;
        }

        public List<JobDetails> getJobDetails() {
            return jobDetails;
        }

        public void setJobDetails(List<JobDetails> jobDetails) {
            this.jobDetails = jobDetails;
        }

        public Set<String> getSkills() {
            return skills;
        }

        public void setSkills(Set<String> skills) {
            this.skills = skills;
        }

         public Integer getTotalExperience() {
            return totalExperience;
        }

        public void setTotalExperience(Integer totalExperience) {
            this.totalExperience = totalExperience;
        }
    }

您的Jobdetail.java

import java.util.Set;    
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlElementWrapper;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement;

@JacksonXmlRootElement(localName="JobDetails")
public class JobDetails {

    public JobDetails() {
    // TODO Auto-generated constructor stub
}
    JobDetails(String str) {

    }

    @JacksonXmlProperty(localName="CompanyName")
    @JsonProperty("CompanyName")
    private String companyName;

    @JacksonXmlProperty(localName="Experience")
    @JsonProperty("Experience")
    private Float experience;

    @JacksonXmlProperty(localName="Location")
    @JsonProperty("Location")
    private String location;

    @JacksonXmlElementWrapper(localName="technologyList")
    @JsonProperty("Technologies")
    private Set<String> technologies;

    public String getCompanyName() {
        return companyName;
    }

    public void setCompanyName(String companyName) {
        this.companyName = companyName;
    }

    public FloatgetExperience() {
        return experience;
    }

    public void setExperience(Floatexperience) {
        this.experience = experience;
    }

    public String getLocation() {
        return location;
    }

    public void setLocation(String location) {
        this.location = location;
    }

    public Set<String> getTechnologies() {
        return technologies;
    }

    public void setTechnologies(Set<String> technologies) {
        this.technologies = technologies;
    }

}

并使用以下方法将xml转换为Json;

public static String convertXMLtoJson( String inputxml) {
         String json="";
         try {
             ObjectMapper objectMapper = new XmlMapper();
             ObjectMapper jsonMapper = new ObjectMapper();
            Employee emp = objectMapper.readValue(inputxml, Employee.class);
          json =jsonMapper.writeValueAsString(emp);
            System.out.println(jsonMapper.writeValueAsString(emp));
         } catch (Exception e) {
             e.printStackTrace();
         }
         return json;
     }

这是我要获取的json数据

{"userId":null,"FirstName":"A","LastName":"Z","Age":20,"Skills":["JAVA","Java","J2EE","MSSQl"],"JobDetails":[{"CompanyName":"1","Experience":1.5,"Location":"India","Technologies":["Java","WebServices","J2EE","MSSQL"]},{"CompanyName":"2","Experience":2.5,"Location":"India","Technologies":["Java","MySQL","J2EE","Spring"]}],"totalExperience":4}