[RESOLVIDO] Exibir toString de atributo ObjectId ao desserializar com jaxb

2 respostas Resolvido
mongodbjsonprogramaçãojava
A

Saudações irmãos de código.

estou aqui estudando mongodb + java e resolvi fazer uma api restfull pra brincar um pouco, ao desserializar o objeto Cliente o atributo id, que é o atributo referente ao campo “_id” da collection no mongodbd, o mesmo vem no seguinte formato:

id: {

timestamp: [telefone removido],

machineIdentifier: 13207740,

processIdentifier: -17673,

counter: 3768415,

time: 1537705891000,

date: 1537705891000,

timeSecond: [telefone removido]

}

a classe cliente se encontra da seguinte forma:

import java.util.List;

import javax.xml.bind.annotation.XmlAccessType;

import javax.xml.bind.annotation.XmlAccessorType;

import javax.xml.bind.annotation.XmlRootElement;

import javax.xml.bind.annotation.XmlValue;

import org.bson.types.ObjectId;

@XmlRootElement

@XmlAccessorType(XmlAccessType.FIELD)

public class Cliente{
private ObjectId id;

private String nome;

private String cpf;

private String rg;

//metodos…

}

porem no lugar de exibir esse atributo desta forma eu gostaria de exibir o método “toString” dese atributo, gostaria de exibir da seguinte forma:

“id” : “5ba7fd625786543ee8260ce2”

alguém sabe como posso fazer isso?

Obrigado a todos

2 Respostas

A

alguem sabe como me ajudar?

A
Solucao aceita

vou colocar aqui a solução, funcionou perfeitamente.

até pq alguém pode precisar dessa informação um dia.

Adapter:

import javax.xml.bind.annotation.adapters.XmlAdapter;

import org.bson.types.ObjectId;

public class ObjectIdAdapter extends XmlAdapter<String, ObjectId>{

<a class="mention" href="/u/override">@Override</a>

public String marshal(ObjectId objectId) throws Exception {

return objectId.toHexString();

}
<a class="mention" href="/u/override">@Override</a>

public ObjectId unmarshal(String id) throws Exception {

return new ObjectId(id);

}

}

Pojo:

import java.util.List;

import javax.xml.bind.annotation.XmlAccessType;

import javax.xml.bind.annotation.XmlAccessorType;

import javax.xml.bind.annotation.XmlRootElement;

import javax.xml.bind.annotation.XmlValue;

import org.bson.types.ObjectId;

@XmlRootElement

@XmlAccessorType(XmlAccessType.FIELD)

public class Cliente{
@XmlJavaTypeAdapter(ObjectIdAdapter.class)

private ObjectId id;

private String nome;

private String cpf;

private String rg;

//metodos…

}

resultado:

{

id: 5bac3f5878436d04f0d7dbbf,

nome: Aala,

cpf : xxx.xxx.xxx-xx,

rg : xx.xxx.xxx-x

}
Criado 28 de setembro de 2018
Ultima resposta 29 de set. de 2018
Respostas 2
Participantes 1