标签: jackson

使用 Jackson 将 JSON 反序列化为包含集合的 Java 对象

我正在和杰克逊做一个非常简单的测试。我有一个类并将其对象用作 Jersey 方法的参数和返回值。班级是:

import java.util.List;

public class TestJsonArray {

    private List<String> testString;

    public List<String> getTestString() {
        return testString;
    }

    public void setTestString(List<String> testString) {
        this.testString = testString;
    }
}
Run Code Online (Sandbox Code Playgroud)

我有一个 Jersey 方法,它尝试将一个字符串添加到列表测试字符串中

@Path("/arrayObj")
    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public Object createObjectArray(@QueryParam("param") String object) throws JsonGenerationException, JsonMappingException, IOException {
        ObjectMapper objectMapper = new ObjectMapper();
        TestJsonArray convertValue = objectMapper.convertValue(object, TestJsonArray.class);
        convertValue.getTestString().add("hello");
        return objectMapper.writeValueAsString(convertValue);
    }
Run Code Online (Sandbox Code Playgroud)

当我用参数调用这个方法时

{"testString":["嗨"]}

我得到一个例外:

java.lang.IllegalArgumentException: Can not construct instance of test.rest.TestJsonArray, problem: no suitable creator method found to deserialize from JSON String …
Run Code Online (Sandbox Code Playgroud)

java json arraylist jackson deserialization

0
推荐指数
1
解决办法
8383
查看次数

简单地图的 Json 序列化导致 stackOverflowErrors

这个简单的代码:

public static void Test() throws JsonProcessingException {
    Map<Object, Object> request = new HashMap<>();
    request.put("id", "test_0001");
    request.put("version", 1);

    Map<Object, Object> fields = new HashMap<>();
    fields.put("uri", "blah/blah");
    fields.put("owner", "me");

    request.put("fields", request);

    ObjectMapper om = new ObjectMapper();
    System.out.println(om.writeValueAsString(request));
}
Run Code Online (Sandbox Code Playgroud)

导致此异常:

Exception in thread "main" java.lang.StackOverflowError
    at java.lang.Enum.ordinal(Enum.java:103)
    at com.fasterxml.jackson.databind.MapperFeature.getMask(MapperFeature.java:259)
    at com.fasterxml.jackson.databind.cfg.MapperConfig.isEnabled(MapperConfig.java:110)
    at com.fasterxml.jackson.databind.SerializationConfig.getAnnotationIntrospector(SerializationConfig.java:404)
    at com.fasterxml.jackson.databind.SerializerProvider.getAnnotationIntrospector(SerializerProvider.java:307)
    at com.fasterxml.jackson.databind.ser.std.MapSerializer.createContextual(MapSerializer.java:235)
    at com.fasterxml.jackson.databind.SerializerProvider._handleContextual(SerializerProvider.java:968)
    at com.fasterxml.jackson.databind.SerializerProvider.findValueSerializer(SerializerProvider.java:447)
    at com.fasterxml.jackson.databind.ser.impl.PropertySerializerMap.findAndAddSerializer(PropertySerializerMap.java:38)
    at com.fasterxml.jackson.databind.ser.std.MapSerializer._findAndAddDynamic(MapSerializer.java:516)
    at com.fasterxml.jackson.databind.ser.std.MapSerializer.serializeFields(MapSerializer.java:386)
    at com.fasterxml.jackson.databind.ser.std.MapSerializer.serialize(MapSerializer.java:312)
    at com.fasterxml.jackson.databind.ser.std.MapSerializer.serialize(MapSerializer.java:26)
etc...
Run Code Online (Sandbox Code Playgroud)

对于我的生活,我无法弄清楚原因。我通过搜索发现的只是人们因为递归引用而遇到问题,但在这种情况下并非如此。

java json jackson

0
推荐指数
1
解决办法
1474
查看次数

JsonParser 返回 null 而不是值

我有一个简单的 Jackson 解析器,它应该返回我的值,但我只得到null值。任何想法将不胜感激?

示例 Json 数据:

{"a":"ab","b":"cd","c":"cd","d":"de","e":"ef","f":"fg"}
Run Code Online (Sandbox Code Playgroud)

代码:

var jfactory = new JsonFactory()
var jParser : JsonParser  = jfactory.createJsonParser(new File(outputDir + "/" + "myDic.json"))

while (jParser.nextToken() != JsonToken.END_OBJECT) {
  var k = jParser.getCurrentName();
  jParser.nextToken();
  var v = jParser.getText();
  println(k +"---" + v)
  phoneDict.put(k,v);
  i = i + 1;
  println(phoneDict.size)
  var t = readLine("Dict Done ?")
}
Run Code Online (Sandbox Code Playgroud)

输出:

null---null
1
Dict Done ?
null---null
1
Dict Done ?
null---null
1
Dict Done ?
null---null
1
Dict Done ?
Run Code Online (Sandbox Code Playgroud)

streaming json scala jackson

0
推荐指数
1
解决办法
2356
查看次数

Java:更新JSON文件中嵌套数组节点的值

由于项目要求,我必须使用com.fasterxml.jackson.databind库来解析JSON数据,不能使用其他可用的JSON库.

我是JSON解析的新手,所以不确定这里是否有更好的选择?

我想知道如何更新ArrayJSON文件中节点的字符串值.

以下是JSON示例.请注意,这不是整个文件内容,而是简化版.

{
  "call": "SimpleAnswer",
  "environment": "prod",
  "question": {
    "assertions": [
      {
        "assertionType": "regex",
        "expectedString": "(.*)world cup(.*)"
      }
    ],
    "questionVariations": [
      {
        "questionList": [
          "when is the next world cup"
        ]
      }
    ]
  }
}
Run Code Online (Sandbox Code Playgroud)

以下是将JSON读入java对象的代码.

byte[] jsonData = Files.readAllBytes(Paths.get(PATH_TO_JSON));
JsonNode jsonNodeFromFile = mapper.readValue(jsonData, JsonNode.class);
Run Code Online (Sandbox Code Playgroud)

要更新根级节点值,例如environmentJSON文件中,我在某些SO线程上找到了以下方法.

ObjectNode objectNode = (ObjectNode)jsonNodeFromFile;
objectNode.remove("environment");
objectNode.put("environment", "test");
jsonNodeFromFile = (JsonNode)objectNode;
FileWriter file = new FileWriter(PATH_TO_JSON);
file.write(jsonNodeFromFile.toString());
file.flush();
file.close();
Run Code Online (Sandbox Code Playgroud)

问题1:这是更新JSON文件中值的唯一方法吗?它是最好的方法吗?我关注双重转换和文件I/O.

问题2:我找不到更新嵌套Array节点值的方法,例如questionList.将问题更新when is …

java arrays json jackson jackson-databind

0
推荐指数
1
解决办法
1146
查看次数

java.lang.NoSuchMethodError:com.fasterxml.jackson.databind.ObjectWriter.forType

访问weblogic中已部署的spring boot应用程序时,出现以下异常

java.lang.NoSuchMethodError: com.fasterxml.jackson.databind.ObjectWriter.forType(Lcom/fasterxml/jackson/databind/JavaType;)Lcom/fasterxml/jackson/databind/ObjectWriter;
    at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.writeInternal(AbstractJackson2HttpMessageConverter.java:285)
    at org.springframework.http.converter.AbstractGenericHttpMessageConverter.write(AbstractGenericHttpMessageConverter.java:106)
    at org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodProcessor.writeWithMessageConverters(AbstractMessageConverterMethodProcessor.java:231)
    at org.springframework.web.servlet.mvc.method.annotation.HttpEntityMethodProcessor.handleReturnValue(HttpEntityMethodProcessor.java:203)
    at org.springframework.web.method.support.HandlerMethodReturnValueHandlerComposite.handleReturnValue(HandlerMethodReturnValueHandlerComposite.java:81)
Run Code Online (Sandbox Code Playgroud)

我的pom.xml中具有以下依赖项

        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>

        </dependency>
Run Code Online (Sandbox Code Playgroud)

即使我从pom.xml中删除了上述依赖关系,也会发生相同的异常

下面是有同样问题的帖子,但没有解决

com.fasterxml.jackson.databind.ObjectWriter.forType(Lcom / fasterxml / jackson / databind / JavaType;)Lcom / fasterxml / jackson / databind / ObjectWriter;

请一些身体帮助我....

以下是pom文件

 <?xml version="1.0" encoding="UTF-8"?>
    <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>com.example</groupId>
        <artifactId>demo</artifactId>
        <version>0.0.1-SNAPSHOT</version>
        <packaging>war</packaging>

    <name>demo</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.4.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->


    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId> …
Run Code Online (Sandbox Code Playgroud)

weblogic jackson spring-boot

0
推荐指数
1
解决办法
6077
查看次数

Jackson,将字符串反序列化为日期

我具有以下JSON属性:

"created_at":"2017-12-08T10:56:01.000Z"
Run Code Online (Sandbox Code Playgroud)

我想使用Jackson以下属性反序列化JSON文档:

@JsonProperty("created_at")
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-ddTHH:mm:ss.SSSZ")
private java.util.Date createdAt;
Run Code Online (Sandbox Code Playgroud)

但失败,但以下异常:

org.springframework.web.client.RestClientException: Could not extract response: no suitable HttpMessageConverter found for response type [class com.example.domain.Product] and content type [application/json;charset=utf-8]
    at org.springframework.web.client.HttpMessageConverterExtractor.extractData(HttpMessageConverterExtractor.java:119)
    at org.springframework.web.client.RestTemplate$ResponseEntityResponseExtractor.extractData(RestTemplate.java:986)
    at org.springframework.web.client.RestTemplate$ResponseEntityResponseExtractor.extractData(RestTemplate.java:969)
    at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:717)
    at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:671)
    at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:587)
Run Code Online (Sandbox Code Playgroud)

我在做什么错以及如何解决?

json jackson resttemplate

0
推荐指数
1
解决办法
762
查看次数

线程“主”中的异常java.lang.NoClassDefFoundError:io / restassured / response / Response

用于登录到Jira localhost的POJO类。

package com.rest.requestpojo;

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class LoginApi {
	
	@SerializedName("username")
	@Expose
	private String username;
	@SerializedName("password")
	@Expose
	private String password;

	public String getUsername() {
	return username;
	}

	public void setUsername(String username) {
	this.username = username;
	}

	public String getPassword() {
	return password;
	}

	public void setPassword(String password) {
	this.password = password;
	}


}
Run Code Online (Sandbox Code Playgroud)

服务类,以从JIRA呼叫后获得响应以进行登录。我只是使用主要方法来检查响应。

package com.rest.services;


import org.json.JSONObject;

import com.rest.requestpojo.LoginApi;

import io.restassured.RestAssured;
import io.restassured.response.Response;
import io.restassured.specification.RequestSpecification;

public class Service 
{
	public Response jiraLoginAuth(String username, String password)
	{
		LoginApi …
Run Code Online (Sandbox Code Playgroud)

java selenium jackson rest-assured jira-rest-api

0
推荐指数
1
解决办法
3095
查看次数

错误com.fasterxml.jackson.databind.exc.MismatchedInputException:由于输入结束而没有要映射的内容

我正在尝试转换下一个字符串:

"{ \"contacts\": [{\"name\":\"1\",\"phone\":\"+123456\"}]}"
Run Code Online (Sandbox Code Playgroud)

到一些自定义对象:

public class CustomObject{

    private List<Contact> contacts;

    public CustomObject(){

    }

    public CustomObject(List<Contact> contacts) {
        this.contacts = contacts;
    }

    public List<Contact> getContactList() {
        return contacts;
    }

    public void setContactList(List<Contact> contacts) {
        this.contacts = contacts;
    }
}
Run Code Online (Sandbox Code Playgroud)

此外,此CustomObject中还有另一个对象:

public class Contact {

    private String name;
    private String phone;

    public Contact() {
    }

    public Contact(String name, String phone) {
        this.name = name;
        this.phone = phone;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name …
Run Code Online (Sandbox Code Playgroud)

java string json jackson objectmapper

0
推荐指数
1
解决办法
3752
查看次数

使用蓝图XML DSL的Camel DataFormat Jackson引发上下文异常

无论我将数据格式放在XML DSL蓝图中的何处,都会在不同的地方开始出现此错误。如果删除它,它可以工作,但是我当然不能将JSON转换为POJO。??? 任何帮助或告诉我我在做错什么,我在想什么。谢谢!

错误

Unable to start blueprint container for bundle passthrumt1.core/1.0.1.SNAPSHOT
Caused by: org.xml.sax.SAXParseException: cvc-complex-type.2.4.a: Invalid content was found starting with element 'endpoint'. One of '{"http://camel.apache.org/schema/blueprint":redeliveryPolicyProfile, "http://camel.apache.org/schema/blueprint":onException, "http://camel.apache.org/schema/blueprint":onCompletion, "http://camel.apache.org/schema/blueprint":intercept, "http://camel.apache.org/schema/blueprint":interceptFrom, "http://camel.apache.org/schema/blueprint":interceptSendToEndpoint, "http://camel.apache.org/schema/blueprint":restConfiguration, "http://camel.apache.org/schema/blueprint":rest, "http://camel.apache.org/schema/blueprint":route}' is expected.
Run Code Online (Sandbox Code Playgroud)

XML DSL

   <camelContext     
      id="com.passthru.coreCamelContext"
      trace="true"
      xmlns="http://camel.apache.org/schema/blueprint"
      allowUseOriginalMessage="false"
      streamCache="true"
      errorHandlerRef="deadLetterErrorHandler" >

    <properties>
        <property key="http.proxyHost" value="PITC-Zscaler-Americas.proxy.corporate.com"/>
        <property key="http.proxyPort" value="80"/>
    </properties>

    <streamCaching  id="CacheConfig" 
                    spoolUsedHeapMemoryThreshold="70" 
                    anySpoolRules="true"/>
<!--  -->
    <dataFormats>
            <json id="Json2Pojo" library="Jackson" unmarshalTypeName="com.passthru.core.entities.TokenEntities">
            </json>
    </dataFormats>

    <endpoint id="predixConsumer" uri="direct:preConsumer" />
    <endpoint id="predixProducer" uri="direct:preProducer" />
    <endpoint id="getToken" uri="direct:getToken" /> …
Run Code Online (Sandbox Code Playgroud)

json dataformat apache-camel jackson spring-camel

0
推荐指数
1
解决办法
390
查看次数

如何在Java的LocalDateTime和LocalDate上配置Jackson序列化?

我知道在Stackoverflow上有很多与此主题相关的文章,我敢肯定我已经阅读了所有这些文章,但是我仍在努力使这项工作正常进行,并且希望获得任何指导。

这是我正在使用的Spring Parent和Jackson依赖关系:

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

<!-- Jackson -->
<dependency>
    <groupId>com.fasterxml.jackson.module</groupId>
    <artifactId>jackson-module-parameter-names</artifactId>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.datatype</groupId>
    <artifactId>jackson-datatype-jdk8</artifactId>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.datatype</groupId>
    <artifactId>jackson-datatype-jsr310</artifactId>
</dependency>
Run Code Online (Sandbox Code Playgroud)

在我的应用程序配置中,我尝试使用:

@Autowired
void configureJackson(ObjectMapper jackson2ObjectMapper) {

    JavaTimeModule timeModule = new JavaTimeModule();

    timeModule.addDeserializer(LocalDate.class,
            new LocalDateDeserializer(DateTimeFormatter.ofPattern("yyyy-MM-dd")));

    timeModule.addDeserializer(LocalDateTime.class,
            new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));

    timeModule.addSerializer(LocalDate.class,
            new LocalDateSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd")));

    timeModule.addSerializer(LocalDateTime.class,
            new LocalDateTimeSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));

    jackson2ObjectMapper
            .configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false)
            .setSerializationInclusion(JsonInclude.Include.NON_NULL)
            .registerModule(timeModule)
            .registerModule(new ParameterNamesModule())
            .registerModule(new Jdk8Module())
            .registerModule(new JtsModule());
}
Run Code Online (Sandbox Code Playgroud)

这是我正在测试的模型。(我试图在5-6个型号中达到相同的效果)。

public class DateRange implements Serializable {

     private static final long serialVersionUID = 6412487507434252330L;

     private LocalDateTime startTime;
     private LocalDateTime endTime; …
Run Code Online (Sandbox Code Playgroud)

java serialization jackson

0
推荐指数
1
解决办法
4502
查看次数