【问题标题】:Issue in parsing jackson解析杰克逊的问题
【发布时间】:2015-08-19 14:44:43
【问题描述】:

我正在使用休息模板获取 json

  RestTemplate restTemplate = new RestTemplate();
    restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
 test = restTemplate.getForObject(url,Test.class, params);

我得到像 json 一样的

{"object":"{\"id\":123,\"userId\":159,\"contentId\":1}"}

这是我的 POJO

@JsonIgnoreProperties(ignoreUnknown = true)
public class Test {
    @JsonProperty("id")
    private String id;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

但我遇到了错误

[Source: sun.net.www.protocol.http.HttpURLConnection$HttpInputStream@9bd513b; line: 1, column: 75] (through reference chain: nested exception is com.fasterxml.jackson.databind.JsonMappingException: Can not instantiate value of type [simple type, class com.soham.Test] from String value ('{"id":123,"userId":116,"contentId":0}'); no single-String constructor/factory method

更新: 我试图添加一个构造函数

public Test(String id){
this.id=id;
}

然后它没有显示错误。但是它正在打印整个 json

{"id":123,"userId":116,"contentId":0}

如何解决?有什么想法吗?

【问题讨论】:

  • 错误消息说明我猜很清楚 - 此外,这里有很多重复项,例如 this f.e
  • @RomanVottner 查看我的更新答案。但是您提到的问题没有接受的答案
  • 你可以试试this approach
  • @RomanVottner 。我希望它可以通过 POJO 映射。我想避免使用 objectMapper
  • 看来你应该添加一个wrapper class

标签: java json jackson spring-boot


【解决方案1】:

在我的情况下,只需从Getting Started restTemplate 页面获取示例 URL 并使用以下代码就可以了:

Maven pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>at.rovo.test</groupId>
    <artifactId>RestTemplate</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>RestTemplate</name>
    <url>http://maven.apache.org</url>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.2.3.RELEASE</version>
    </parent>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
    <repositories>
        <repository>
            <id>spring-releases</id>
            <url>https://repo.spring.io/libs-release</url>
        </repository>
    </repositories>

    <pluginRepositories>
        <pluginRepository>
            <id>spring-releases</id>
            <url>https://repo.spring.io/libs-release</url>
        </pluginRepository>
    </pluginRepositories>
</project>

豆类:

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;

@JsonIgnoreProperties(ignoreUnknown = true)
public class Test
{
    @JsonProperty("id")
    private long id;
    private String name;
    private String about;
    private String phone;
    private String website;

    public Test()
    {

    }

    public void setId(long id)
    {
        this.id = id;
    }

    public long getId()
    {
        return this.id;
    }

    public String getName()
    {
        return name;
    }

    public void setName(String name)
    {
        this.name = name;
    }

    public String getAbout()
    {
        return about;
    }

    public void setAbout(String about)
    {
        this.about = about;
    }

    public String getPhone()
    {
        return phone;
    }

    public void setPhone(String phone)
    {
        this.phone = phone;
    }

    public String getWebsite()
    {
        return website;
    }

    public void setWebsite(String website)
    {
        this.website = website;
    }
}

最后但并非最不重要的是指定 restTemplate 的类,它还使用给定的 URL(取自入门页面)调用 restTemplate 并将几个属性打印到控制台:

import java.util.ArrayList;
import java.util.List;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.http.converter.FormHttpMessageConverter;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.client.RestTemplate;

public class App 
{
    public static void main( String[] args )
    {
        RestTemplate restTemplate = new RestTemplate();
        List<HttpMessageConverter<?>> messageConverters = new ArrayList<HttpMessageConverter<?>>();
        messageConverters.add(new FormHttpMessageConverter());
        messageConverters.add(new StringHttpMessageConverter());
        messageConverters.add(new MappingJackson2HttpMessageConverter());
        restTemplate.setMessageConverters(messageConverters);

        restTemplate.setRequestFactory(new HttpComponentsClientHttpRequestFactory());
        String url = "http://graph.facebook.com/pivotalsoftware";
        Test response = restTemplate.getForObject(url, Test.class);

        System.out.println("Id: " + response.getId());
        System.out.println("Name: " + response.getName());
        System.out.println("Phone: " + response.getPhone());
        System.out.println("About: " + response.getAbout());
    }
}

【讨论】:

  • 我正在使用spring-boot,所以我不需要杰克逊的maven依赖。虽然我无法解决它,但它给出了同样的错误。
【解决方案2】:

根据我使用 Spring REST 的经验,实体对象的构造函数(在本例中是您的 Test 类)不应该带任何参数。看到 Roman Vottner 的回应似乎证实了这一点。

【讨论】:

    【解决方案3】:

    我能解决。这是我的解决方案

        @JsonIgnoreProperties(ignoreUnknown = true)
        @JsonAutoDetect(creatorVisibility = JsonAutoDetect.Visibility.ANY)
        @JsonInclude(JsonInclude.Include.NON_NULL)
        public class Test {
    
            @JsonProperty("id")
            private String id;
            @JsonProperty("userId")
            private int userId;
            @JsonProperty("contentId")
            private int contentId;
           public Test() {
    
        }
    
        @JsonCreator
        public static Test getJson(String json) throws IOException {
            ObjectMapper mapper = new ObjectMapper();
            return mapper.readValue(json, Test.class);
        }
    
            public String getId() {
                return id;
            }
    
            public void setId(String id) {
                this.id = id;
            }
            public String getContentId() {
                return contentId;
            }
    
            public void setContentId(String contentId) {
                this.contentId = contentId;
            }
             public int getUserId() {
                return userId;
            }
    
            public void setUserId(int userId) {
                this.userId = userId;
            }
        }
    

    【讨论】:

    • @scottb 明天才可以。
    猜你喜欢
    • 2016-05-15
    • 2014-06-17
    • 1970-01-01
    • 1970-01-01
    • 2019-07-27
    • 2018-08-25
    • 2014-08-22
    • 2019-11-25
    • 1970-01-01
    相关资源
    最近更新 更多