Java无法解析JSON.stringfy生成的JSON

时间:2016-06-28 18:33:47

标签: java json java-ee

从rc-1升级到rc-3后,JSON.stringfy()方法会在每个值的开头和结尾返回\的值:

{
    \"perfil\":\"CLIENTE\", ...
}

我该如何解决这个问题?

代码段:

post(url, data) {
    console.log(JSON.stringify(data));
    return Observable.create(observer =>
        this.http.post(this.restConfig.baseUrl + url, JSON.stringify(data), {
            headers: this.getDefaultHeaders()
        }).subscribe(
            data => this.next(observer, data)
            , err => {
                console.log(err);
                if (err.status === 401) {
                    this.redirectAuth();
                }
                observer.error(err);
            }
        )
    );
}

我的Java RESTful服务无法解析输出:

Unexpected token (VALUE_STRING), expected FIELD_NAME: missing property 'perfil' that is to contain type id  (for class br.com.inbit.medipop.model.entities.impl.Cliente) at [Source: java.io.ByteArrayInputStream@79f844cf; line: 1, column: 1]

class Cliente:

@Table
@Entity
@DiscriminatorValue("CLIENTE")
public class Cliente extends Usuario {

}

类Usuario:

@Table
@Entity
@Inheritance(strategy = InheritanceType.JOINED)
@DiscriminatorColumn(name = "perfil", discriminatorType = DiscriminatorType.STRING)
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "perfil")
@JsonSubTypes({
    @JsonSubTypes.Type(value = Administrador.class, name = "ADMIN"),
    @JsonSubTypes.Type(value = Colaborador.class, name = "COLABORADOR"),
    @JsonSubTypes.Type(value = Parceiro.class, name = "PARCEIRO"),
    @JsonSubTypes.Type(value = Cliente.class, name = "CLIENTE"),
    @JsonSubTypes.Type(value = Dependente.class, name = "DEPENDENTE")
})
public abstract class Usuario {

    @NotNull
    @Enumerated(EnumType.STRING)
    @Column(insertable = false, updatable = false)
    protected PerfilUsuario perfil;

    ...
}

stringfy之前的数据:

{"perfil":"CLIENTE","pessoa":{"tipo":"FISICA","sexo":"MASCULINO","nome":"Marcos Kichel","cpf":"911.111.064-36","rg":"1234"},"dependentes":[],"email":"anackichel@gmail.com"}

2 个答案:

答案 0 :(得分:1)

您似乎正在对已经字符串化的内容进行字符串化。取出JSON.stringify(),你应该好好去。

答案 1 :(得分:0)

此处的问题实际上并非由转义引号引起,而是perfil字段的错误数据类型。在您的Java代码中,它应该是一个对象,而在json中,您传递String值"CLIENTE"

因此,要么确保在" perfil"内发送一个对象。字段或将perfil字段的类型从PerfilUsuario更改为字符串