GVKun编程网logo

在包含JsonIdentityInfo的JavaScript中反序列化Jackson对象(json含有特殊字符反序列化报错)

15

本文将为您提供关于在包含JsonIdentityInfo的JavaScript中反序列化Jackson对象的详细介绍,我们还将为您解释json含有特殊字符反序列化报错的相关知识,同时,我们还将为您提供

本文将为您提供关于在包含JsonIdentityInfo的JavaScript中反序列化Jackson对象的详细介绍,我们还将为您解释json含有特殊字符反序列化报错的相关知识,同时,我们还将为您提供关于@JsonIdentityInfo注解在Java中使用Jackson的重要性是什么?、asp.net – 如何使用JSON方法序列化javascript对象、com.fasterxml.jackson.annotation.JsonIdentityInfo的实例源码、Jackson Mapper没有反序列化JSON – (无法读取JSON:已经有了id(java.lang.Integer)的POJO)的实用信息。

本文目录一览:

在包含JsonIdentityInfo的JavaScript中反序列化Jackson对象(json含有特殊字符反序列化报错)

在包含JsonIdentityInfo的JavaScript中反序列化Jackson对象(json含有特殊字符反序列化报错)

我正在使用angularjs前端网站使用Web服务,并使用SPRING MVC生成json。spring mvc使用JsonIdentityInfo选项进行序列化,因此每个对象仅在json中写入一次,并且每次都使用引用进行写入,例如她使用相同的对象“ component”有2个“ computer”,因此spring将ID设置为第一个组件(“ @componentID”:2),第二个组件的ID为(2):

[  {    "@computerID": 1,    "component": {      "@componentID": 2,      "processor": 2,      "ram": "8g",      "harddrive": "wd"    }  },  {    "@computerID": 3,    "component": 2  }]

我想要的是 :

[  {    "@computerID": 1,    "owner" : "Mister B",    "component": {      "@componentID": 2,      "processor": 2,      "ram": "8g",      "harddrive": "wd"    }  },  {    "@computerID": 3,    "owner" : "Mister A",    "component": {      "@componentID": 2,      "processor": 2,      "ram": "8g",      "harddrive": "wd"    }  }]

我搜索了很多执行此操作的代码,但没有找到任何想法。

我无法编辑Web服务以删除此行为。我可以使用javascript或jquery(或其他librairie)在客户端编辑json,以将引用替换为实际引用的对象吗?(数据实际上更复杂,更深入,我在对象中有3级子对象)。

非常感谢。

答案1

小编典典

我最近遇到了OP在这里描述的确切场景。下面是我的解决方案。使用JSOG(Javascript对象图)格式可以解决此问题。

服务器端使用Jackson-Jsog插件https://github.com/jsog/jsog-jackson 并使用以下注释对每个类进行注释。

@JsonIdentityInfo(generator=JSOGGenerator.class)

而不是

@JsonIdentityInfo(generator = ObjectIdGenerators.IntSequenceGenerator.class, property = "@id")

这将以JSOG格式生成。(@id@ref

在客户端上,使用jsog.js

使用以下调用将JSOG结构转换为循环结构

cyclicGraph = JSOG.decode(jsogStructure);

@JsonIdentityInfo注解在Java中使用Jackson的重要性是什么?

@JsonIdentityInfo注解在Java中使用Jackson的重要性是什么?

@jsonidentityinfo注解在java中使用jackson的重要性是什么?

当对象在 Jackson 库中具有父子关系时,将使用@JsonIdentityInfo注释。 @JsonIdentityInfo 注解 用于在序列化和反序列化过程中指示对象身份。 ObjectIdGenerators.PropertyGenerator 是一个抽象占位符类,用于表示要使用的对象标识符来自 POJO 属性的情况。

语法

@Target(value={ANNOTATION_TYPE,TYPE,FIELD,METHOD,PARAMETER})
@Retention(value=RUNTIME)
public @interface JsonIdentityInfo
登录后复制

示例

import java.util.*;
import java.io.*;
import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.fasterxml.jackson.annotation.ObjectIdGenerators;
import com.fasterxml.jackson.databind.ObjectMapper;
public class JsonIdentityInfoTest {
   public static void main(String[] args) throws IOException {
      ObjectMapper mapper = new ObjectMapper();
      User user = new User(115, "Raja", "Ramesh");
      Address address = new Address(125, "Madhapur", "Hyderabad", user);
      user.addAddress(address);
      String jsonString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(address);
      System.out.println(jsonString);
   }
}
// User class
@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "userId")
class User {
   private int userId;
   private String firstName;
   private String lastName;
   private List<Address> addresses;
   public User(int userId, String firstName, String lastName) {
      this.userId = userId;
      this.firstName = firstName;
      this.lastName = lastName;
      this.addresses = new ArrayList<Address>();
   }
   public int getUserId() {
      return userId;
   }
   public String getFirstName() {
      return firstName;
   }
   public String getLastName() {
      return lastName;
   }
   public void addAddress(Address address) {
      addresses.add(address);
   }
}
// Address class
@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "userId")<strong>
</strong>class Address {
   private int userId;
   private String city;
   private String street;
   private User user;
   public Address(int userId, String street, String city, User user) {
      this.userId = userId;
      this.street = street;
      this.city = city;
      this.user = user;
   }
   public int getUserId() {
      return userId;
   }
   public String getStreet() {
      return street;
   }
   public String getCity() {
      return city;
   }
   public User getUser() {
      return user;
   }
}
登录后复制

输出

{
 "userId" : 125,
 "city" : "Hyderabad",
 "street" : "Madhapur",
 "user" : {
    "userId" : 115,
    "firstName" : "Raja",
    "lastName" : "Ramesh"
    }
}
登录后复制

以上就是@JsonIdentityInfo注解在Java中使用Jackson的重要性是什么?的详细内容,更多请关注php中文网其它相关文章!

asp.net – 如何使用JSON方法序列化javascript对象

asp.net – 如何使用JSON方法序列化javascript对象

我正在寻找 JSON的增强功能,它也会序列化方法.我有一个对象作为对象的集合,并希望序列化集合对象的方法.到目前为止我找到了 ClassyJSON.有什么想法吗?

解决方法

我认为序列化方法不是一个好主意.如果您打算运行代码服务器端,那么您可以打开攻击.如果你想在客户端运行它,你最好只使用本地方法,可能引用你将在序列化对象中使用的方法的名称.

我确实相信“f =”function(){}会产生一个你可以评估的字符串版本:

var test = "f = " + function() { alert("Hello"); };
eval(test)

对于良好的json处理,我建议使用prototype,它有很好的方法将对象序列化为json.

com.fasterxml.jackson.annotation.JsonIdentityInfo的实例源码

com.fasterxml.jackson.annotation.JsonIdentityInfo的实例源码

项目:teavm-flavour    文件:ClassinformationProvider.java   
private void getIdentityInfo(Classinformation information,ReflectClass<?> cls) {
    JsonIdentityInfo identity = cls.getAnnotation(JsonIdentityInfo.class);
    if (identity == null) {
        return;
    }

    Class<?> generator = identity.generator();
    if (generator.equals(ObjectIdGenerators.IntSequenceGenerator.class)) {
        information.idGenerator = IdGeneratorType.INTEGER;
    } else if (generator.equals(ObjectIdGenerators.PropertyGenerator.class)) {
        information.idGenerator = IdGeneratorType.PROPERTY;
    } else if (generator.equals(ObjectIdGenerators.None.class)) {
        information.idGenerator = IdGeneratorType.NONE;
    } else {
        information.idGenerator = IdGeneratorType.NONE;
        diagnostics.warning(null,"{{t0}}: unsupported identity generator {{t1}}",cls,generator);
    }

    if (information.idGenerator == IdGeneratorType.NONE) {
        information.idProperty = null;
    } else {
        information.idProperty = identity.property();
    }
}
项目:dhis2-core    文件:Option.java   
@JsonProperty
@JacksonXmlElementWrapper( localName = "organisationUnits",namespace = DxfNamespaces.DXF_2_0 )
@JacksonXmlProperty( localName = "organisationUnit",namespace = DxfNamespaces.DXF_2_0 )
@JsonIdentityInfo(generator=ObjectIdGenerators.PropertyGenerator.class,property="id")
@JsonIdentityReference(alwaysAsId=true)
public Set<OrganisationUnit> getorganisationUnits()
{
    return organisationUnits;
}
项目:QuizUpWinner    文件:JacksonAnnotationIntrospector.java   
public ObjectIdInfo findobjectIdInfo(Annotated paramAnnotated)
{
  JsonIdentityInfo localJsonIdentityInfo = (JsonIdentityInfo)paramAnnotated.getAnnotation(JsonIdentityInfo.class);
  if ((localJsonIdentityInfo == null) || (localJsonIdentityInfo.generator() == ObjectIdGenerators.None.class))
    return null;
  return new ObjectIdInfo(localJsonIdentityInfo.property(),localJsonIdentityInfo.scope(),localJsonIdentityInfo.generator());
}
项目:gwt-jackson    文件:PropertyProcessor.java   
private static void processBeanAnnotation( TreeLogger logger,JacksonTypeOracle typeOracle,RebindConfiguration configuration,JType
        type,PropertyAccessors propertyAccessors,PropertyInfoBuilder builder ) throws UnabletoCompleteException {

    // identity
    Optional<JsonIdentityInfo> jsonIdentityInfo = propertyAccessors.getAnnotation( JsonIdentityInfo.class );
    Optional<JsonIdentityReference> jsonIdentityReference = propertyAccessors.getAnnotation( JsonIdentityReference.class );

    // type info
    Optional<JsonTypeInfo> jsonTypeInfo = propertyAccessors.getAnnotation( JsonTypeInfo.class );
    Optional<JsonSubTypes> propertySubTypes = propertyAccessors.getAnnotation( JsonSubTypes.class );

    // if no annotation is present that overrides bean processing,we just stop Now
    if ( !jsonIdentityInfo.isPresent() && !jsonIdentityReference.isPresent() && !jsonTypeInfo.isPresent() && !propertySubTypes
            .isPresent() ) {
        // no override on field
        return;
    }

    // we need to find the bean to apply annotation on
    Optional<JClasstype> beanType = extractBeanType( logger,typeOracle,type,builder.getPropertyName() );

    if ( beanType.isPresent() ) {
        if ( jsonIdentityInfo.isPresent() || jsonIdentityReference.isPresent() ) {
            builder.setIdentityInfo( BeanProcessor.processIdentity( logger,configuration,beanType
                    .get(),jsonIdentityInfo,jsonIdentityReference ) );
        }

        if ( jsonTypeInfo.isPresent() || propertySubTypes.isPresent() ) {
            builder.setTypeInfo( BeanProcessor.processtype( logger,jsonTypeInfo,propertySubTypes ) );
        }
    } else {
        logger.log( Type.WARN,"Annotation present on property " + builder.getPropertyName() + " but no valid bean has been found." );
    }
}
项目:GitHub    文件:ByIdProperty.java   
@JsonIdentityReference(alwaysAsId = true)
@JsonIdentityInfo(
    resolver = ByidInstanceResolver.class,generator = ObjectIdGenerators.PropertyGenerator.class,property = "id")
Byid b();
项目:turing    文件:TurDataGroupSentence.java   
@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class,property = "id")
@JsonIdentityReference(alwaysAsId = true)
public TurmlCategory getTurmlCategory() {
    return this.turmlCategory;
}
项目:gwt-jackson    文件:BeanProcessor.java   
private static Optional<BeanIdentityInfo> processIdentity( TreeLogger logger,RebindConfiguration
        configuration,JClasstype type ) throws UnabletoCompleteException {
    return processIdentity( logger,Optional.<JsonIdentityInfo>absent(),Optional
            .<JsonIdentityReference>absent() );
}
项目:gwt-jackson    文件:ObjectIdDeserializationTester.java   
public IdParameterWrapper( @JsonProperty( "node" ) @JsonIdentityInfo( generator = ObjectIdGenerators.IntSequenceGenerator.class,property = "@id" ) ValueParameterNode node ) {
    this.test = node;
}
项目:gwt-jackson    文件:ObjectIdDeserializationTester.java   
public IdParameterWrapperExt( @JsonProperty( "node" ) @JsonIdentityInfo( generator = ObjectIdGenerators.PropertyGenerator.class,property = "customId" ) ValueParameterNodeExt node ) {
    this.test = node;
}
项目:immutables    文件:ByIdProperty.java   
@JsonIdentityReference(alwaysAsId = true)
@JsonIdentityInfo(
    resolver = ByidInstanceResolver.class,property = "id")
Byid b();

Jackson Mapper没有反序列化JSON – (无法读取JSON:已经有了id(java.lang.Integer)的POJO)

Jackson Mapper没有反序列化JSON – (无法读取JSON:已经有了id(java.lang.Integer)的POJO)

在将json发布到Spring Controller时获得上述异常.看来Jackson Mapper无法反序列化json. CategoryDTO注释为:

@JsonIdentityInfo(generator=ObjectIdGenerators.IntSequenceGenerator.class,property="@id",scope = CategoryDTO.class)

JSON:

[
   {
      "categories":[
         {
            "@id":27048,"name":"Sportbeha's","description":null,"parent":{
               "@id":22416,"name":"fitness","parent":{
                  "@id":21727,"name":"Collectie","description":null
               }
            }
         },{
            "@id":27050,"parent":{
               "@id":24474,"name":"Voetbal","parent":21727
            }
         }
      ]
   },{
      "categories":[
         {
            "@id":27048,"parent":21727
            }
         }
      ]
   }
]

Java代码:

@JsonSerialize(include= JsonSerialize.Inclusion.NON_NULL)
@JsonIdentityInfo(generator=ObjectIdGenerators.IntSequenceGenerator.class,scope = CategoryDTO.class)
@JsonIgnoreProperties(ignoreUnkNown = true)
public class CategoryDTO implements Serializable{

    private Long id;
    private String name;
    private String description;
    private CategoryDTO parent;

    @JsonIgnore
    public Long getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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


    public String getDescription() {
        return description;
    }

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

    public CategoryDTO getParent() {
        return parent;
    }

    public void setParent(CategoryDTO parent) {
        this.parent = parent;
    }

}


**Spring Controller :** 

    @RequestMapping(value = "/categories",method = RequestMethod.POST,consumes =  "application/json;charset=UTF-8",produces = "application/json;charset=UTF-8")
    public ResponseEntity

问题似乎与这片json有关:

"parent":{
    "@id":21727,"description":null
}

它存在于数组中的两个对象中.

最佳答案
如果对每个嵌套对象使用相同的CategoryDto,

"parent": 21727

因为杰克逊期待一个对象,所以不会反序列化.要仅使用id反序列化父CategoryDto,您需要POST以下JSON:

"parent": {
    "@id": 21727
}

今天的关于在包含JsonIdentityInfo的JavaScript中反序列化Jackson对象json含有特殊字符反序列化报错的分享已经结束,谢谢您的关注,如果想了解更多关于@JsonIdentityInfo注解在Java中使用Jackson的重要性是什么?、asp.net – 如何使用JSON方法序列化javascript对象、com.fasterxml.jackson.annotation.JsonIdentityInfo的实例源码、Jackson Mapper没有反序列化JSON – (无法读取JSON:已经有了id(java.lang.Integer)的POJO)的相关知识,请在本站进行查询。

本文标签: