Marcos J.C Kichel
Marcos J.C Kichel

Reputation: 7219

Java can't parse JSON generated by JSON.stringfy

After upgrading from rc-1 to rc-3 the JSON.stringfy() method is returning values with \ at start and end of each value:

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

How should I fix that?

code snippet:

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);
            }
        )
    );
}

My Java RESTful services can't parse the output:

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 {

}

class 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;

    ...
}

data before stringfy:

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

Upvotes: 0

Views: 124

Answers (2)

Jarod Moser
Jarod Moser

Reputation: 7358

It seems that you are stringifying something that was already stringified. Take out the JSON.stringify() and you should be good to go.

Upvotes: 1

ikryvorotenko
ikryvorotenko

Reputation: 1433

The issue here actually not caused by escaped quotes, but the wrong data type of perfil field. In your java code it's expected to be an object, while in json you pass the String value "CLIENTE".

So either make sure you send an object within "perfil" field or change the type of perfil field from PerfilUsuario to String

Upvotes: 0

Related Questions