我使用jackson将JSON转换为Object类.
JSON:
{
"aaa":"111",
"bbb":"222",
"ccc":"333"
}
Run Code Online (Sandbox Code Playgroud)
对象类:
class Test{
public String aaa;
public String bbb;
}
Run Code Online (Sandbox Code Playgroud)
码:
ObjectMapper mapper = new ObjectMapper();
Object obj = mapper.readValue(content, valueType);
Run Code Online (Sandbox Code Playgroud)
我的代码抛出异常:
org.codehaus.jackson.map.exc.UnrecognizedPropertyException: Unrecognized field "cccc" (Class com.isoftstone.banggo.net.result.GetGoodsInfoResult), not marked as ignorable
Run Code Online (Sandbox Code Playgroud)
而且我不想为类Test添加一个道具,我只想让jackson转换存在的值,而测试中也存在.
我有一个实体(使用lombok)和一些带注释的@JsonView注释.
@Entity
@Table(name = "`order`")
@Getter
@Setter
@ToString
@Description("??????")
public class Order extends Auditable {
private static final long serialVersionUID = -1299630493411381582L;
@JsonView(JsonViews.OrderAdvancedSearch.class)
@ManyToOne
private School school;
@Column(length = 50)
private String number;
}
Run Code Online (Sandbox Code Playgroud)
有一个用@JsonView注释注释的控制器方法.
@Secured(value = {"ROLE_AUTHENTICATED_USER"})
@RequestMapping(value = "/order", method = RequestMethod.GET, headers = {"Content-Type=application/json"})
@JsonView(JsonViews.OrderAdvancedSearch.class)
@ResponseBody
public ResponseEntity<Order> getOrder(HttpServletRequest request) throws IOException, DnevnikException, RestException {
Order order = orderRepository.findOne(292L); // just for example
return new ResponseEntity<>(order,HttpStatus.OK);
}
Run Code Online (Sandbox Code Playgroud)
我希望输入只包含用@JsonView注释的字段.但我充满了田野.
我正在尝试调试spring和jackson来源.在com.fasterxml.jackson.databind.SerializationConfig中,我看到活动视图是我的类JsonViews.OrderAdvancedSearch.class但是在com.fasterxml.jackson.databind.ser.std.BeanSerializerBase变量中,filteredProps始终具有我的实体的所有属性.
我熟悉正常的多态反序列化内容,您可以根据某个字段的字符串值反序列化对象.例如:
@JsonSubTypes(
{
@JsonSubTypes.Type(value = LionCage.class, name = "LION"),
@JsonSubTypes.Type(value = TigerCage.class, name = "TIGER"),
}
)
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type")
Run Code Online (Sandbox Code Playgroud)
如果传入对象的"type"字段是整数而不是字符串,有什么方法可以做同样的事情吗?所以在上面的例子中,"LION"和"TIGER"将是1和2.无论出于何种原因,我都无法弄清楚这一点.
另外,我应该如何解决这个问题?似乎它应该是明显的东西.
最简单的案例给我带来了麻烦.我第一次遇到它.我能够解组稍微复杂的json,但这个简单的失败了.
什么会导致这个以及为什么杰克逊只用一根绳子就麻烦了?
一个包含用户角色名称的简单类.
public class UpdateUserRole {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Run Code Online (Sandbox Code Playgroud)
控制器内部
public void updateUserRole(@PathVariable Long id, @RequestBody UpdateUserRoleReq req) {
}
Run Code Online (Sandbox Code Playgroud)
一旦杰克逊看到这个,它就会抛出这个错误
org.springframework.http.converter.HttpMessageNotReadableException: Could not read JSON: Can not instantiate value of type [simple type, class com.mycompany.UpdateUserRoleReq] from String value ('{"name":"admin_1407445357682"}'); no single-String constructor/factory method; nested exception is com.fasterxml.jackson.databind.JsonMappingException: Can not instantiate value of type [simple type, class com.mycompany.UpdateUserRoleReq] from String value ('{"name":"admin_1407445357682"}'); …Run Code Online (Sandbox Code Playgroud) Jackson框架提供了基于注释的方法,用于在序列化过程中发出类型信息.
我不想在我的超类(Animal)中使用@JsonSubTypes注释.
相反,我想告诉我的SubClasses,即狗和大象,动物是他们的父母.
是否有任何方法可以在不使用Animal类中的注释的情况下执行此操作.
如果是,请提供如果可能的话做同样的例子.
以下是我试图解决的情况."测试"接收的JSON,包含"类型"字段为"狗"或"大象".
我想将这两个类注册为"Animal"类的子类型,但不想在Animal中使用@JsonSubTypes.
任何帮助,将不胜感激.提前致谢.
@JsonTypeInfo( use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type")
abstract class Animal(){
private String sound;
private String type;
//getters and setters
}
@JsonTypeName("dog")
Class Dog extends Animal(){
//some attributes.
//getters and setters
}
@JsonTypeName("elephant")
Class Elephant extends Animal(){
//some attributes.
//getters and setters
}
@Controller
public class MyController {
//REST service
@RequestMapping( value = "test")
public @ResponseBody String save(@RequestBody Animal animal){
System.out.println(animal.getClass());
return success;
}
}
Run Code Online (Sandbox Code Playgroud) 我有一段代码从输入流中读取JSON数据并将其转换为POJO(使用Jackson).有时,数据将无法反序列化,并且很难进行故障排除.在log4j中查看逐行输入流的好机制是什么?是否有其他工具/技术可以帮助进行故障排除?
在使用Jackson解析器时,如何将JSON名称映射到Java类的字段名称(可能略有不同)?
我有传入的JSON文档,我想使用Jackson解析器转换为Java对象.这适用于JSON名称与最终Java对象字段名称匹配的位置(我在Play框架中执行此操作).
但是,传入的JSON文档中的某些JSON名称不适合使用不错的Java字段名称.目前,更改所有现有JSON文档以使用适当的Java命名约定是不可行的.
例如
{
"goodName": "value",
"not-so-handy": "value"
}
Run Code Online (Sandbox Code Playgroud)
我不能创建一个字段名称为"not-so-handy"的Java类,因为它不是Java中的合法名称.
如何使用Jackson解析器将传入的JSON名称转换为指定的Java类的字段名称?
在我的项目中,我有一些JsonDeserializers 来反序列化集合中的抽象类型。现在我有一个有Collection属性的类型。我如何指示杰克逊为我反序列化嵌套集合而不是自己做?
interface Person {
String getName();
void setName(String name);
}
class LonelyPerson implements Person { ... }
class SocialPerson implements Person {
private List<Person> friends;
...
}
public class SocialPersonDeserializer extends JsonDeserializer<Person> {
public Person deserialize(final JsonParser jp, final DeserializationContext ctx) throws IOException {
ObjectCodec codec = jp.getCodec();
JsonNode jsonNode = codec.readTree(jp);
String name = jsonNode.get("name").asText();
SocialPerson sp = new SocialPerson();
p.setName(name);
JsonNode friends = jsonNode.get("name").asText();
for (JsonNode friendNode : friends) {
sp.getFriends().add(/* How to …Run Code Online (Sandbox Code Playgroud) 我正在创建一个新的Jersey 2.21,Jackson 2.6.1 REST服务器(我尝试使用Jersey 2.19和Jackson 2.5.3)并希望使用@InjectLink为我的呼叫者提供HATEOAS链接(如'self').最基本的应用程序(取自Jersey doc和Jersey示例应用程序)不起作用,我无法弄清楚原因.
我首先从Jersey文档中获取基本的Widgets类,但返回的JSON或XML只是一个空结构.
XML:
<Widgets/>
Run Code Online (Sandbox Code Playgroud)
JSON:
{}
Run Code Online (Sandbox Code Playgroud)
Widgets.java
package org.glassfish.jersey.examples.linking;
import java.net.URI;
import java.util.List;
import javax.ws.rs.core.Link;
import javax.xml.bind.annotation.XmlRootElement;
import org.glassfish.jersey.linking.InjectLink;
import org.glassfish.jersey.linking.InjectLinks;
@XmlRootElement()
public class Widgets {
@InjectLink(resource=WidgetsResource.class)
URI u;
@InjectLinks({@InjectLink(resource=WidgetsResource.class, rel = "self")})
List<Link> links;
public Widgets() {}
}
Run Code Online (Sandbox Code Playgroud)
我在资源代码中放了一个断点并检查了返回的对象.it.links和it.u都是null.什么也没注入.
WidgetsResource.java
@Path("widgets")
public class WidgetsResource {
@GET
public Widgets get() {
Widgets it = new Widgets();
return it;
}
}
Run Code Online (Sandbox Code Playgroud)
Maven依赖:
<dependencies>
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-servlet</artifactId>
<version>${jersey.version}</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.ext</groupId>
<artifactId>jersey-declarative-linking</artifactId>
<version>${jersey.version}</version>
</dependency> …Run Code Online (Sandbox Code Playgroud) 我试图从项目中的pojos自动生成JsonSchema:代码如下所示:
ObjectMapper mapper = new ObjectMapper();
SchemaFactoryWrapper visitor = new SchemaFactoryWrapper();
mapper.acceptJsonFormatVisitor(clazz, visitor);
JsonSchema jsonSchema = visitor.finalSchema();
String schemaString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(jsonSchema);
Run Code Online (Sandbox Code Playgroud)
当clazz这样定义时:
public class ZKBean
{
public String anExample;
public int anInt;
}
I end up with this:
{
"type" : "object",
"id" : "urn:jsonschema:com:emc:dpad:util:ZKBean",
"properties" : {
"anInt" : {
"type" : "integer"
},
"anExample" : {
"type" : "string"
}
}
}
Run Code Online (Sandbox Code Playgroud)
一切都很棒。我想做的是在架构中添加“ description”键,这样我将得到如下所示的内容:
{
"type" : "object",
"id" : "urn:jsonschema:com:emc:dpad:util:ZKBean",
"properties" : {
"anInt" : {
"type" …Run Code Online (Sandbox Code Playgroud) jackson ×10
json ×10
java ×9
spring-mvc ×2
hateoas ×1
inputstream ×1
jersey-2.0 ×1
json-view ×1
jsonschema ×1
maven ×1
spring ×1