viernes, 30 de noviembre de 2012

Enlaces sobre herramientas de desarrollo


Branching con Git muy bien explicado

Flujos de Git

Uno de mis vicios. Los juegos

En los siguientes lugares encontrarás miles de horas de diversión.

Humble Bundle
Elige lo que quieres pagar por los juegos, cada cierto tiempo ofrecen packs muy interesantes. Puedes suscribirte para que te avisen.


GOG
Juegos que nunca mueren muy muy buenos. Podrás jugar en los modernos ordenadores juegos clasicos.

Steam
El monopolio de las descargas de juego. Todo tipo de juegos antiguos, nuevos, indies. Suele haber ofertas por temporada y algunos días.

lunes, 26 de noviembre de 2012

Deserializacion de JSON con la librería de Java Jackson

Después de probar varias librerías para Java que me ayudasen a serializar/deserializar JSON, me decanté por Jackson por ser la más completa y que además me permitía el acceso a bajo nivel.

El motivo de esta entrada es enseñar la deserialización usando el acceso a bajo nivel (Streaming) y combinarlo con el acceso de más alto nivel (Data Object binding)

Nuestro objeto JSON se compone de un Objeto con varias propiedades, una de las cuales es un array de otro tipo de objecto:

{"usuarioId":1,"color":4,
"lista":[{"tipo":1,"id":1005,"cantidad":3},
{"tipo":1,"id":1006,"cantidad":4},
{"tipo":1,"id":1007,"cantidad":2}]}

En el siguiente trozo de código vamos a parsear el JSON recibido en un parámetro "data" de la llamada de un webservice:

public void webservice( HttpServletRequest request, HttpServletResponse response ) {
int error = 0;
    
 
JsonParser jp = null;

try {
String datos = request.getParameter("data");
JsonFactory f = new MappingJsonFactory();
jp = f.createJsonParser(datos);

JsonToken current;

current = jp.nextToken();
if (current != JsonToken.START_OBJECT) {
System.out.println("Error: root should be object: quiting.");
return;
}

while (jp.nextToken() != JsonToken.END_OBJECT) {
String fieldName = jp.getCurrentName();
// move from field name to field value
current = jp.nextToken();

if ( fieldName=="usuarioId" ) {
System.out.println("Procesando: " + fieldName + " valor: " + jp.getValueAsString());
jp.skipChildren();
} else if (fieldName=="color") {
System.out.println("Procesando: " + fieldName + " valor: " + jp.getValueAsString());
jp.skipChildren();
} else if (fieldName.equals("lista")) {
if (current == JsonToken.START_ARRAY) {
// For each of the records in the array
while (jp.nextToken() != JsonToken.END_ARRAY) {
// read the record into a tree model,
// this moves the parsing position to the end of it

//JsonNode node = jp.readValueAsTree();
// And now we have random access to everything in the object
//System.out.println("tipo: " + node.get("tipo").asText());
//System.out.println("id: " + node.get("id").asText());

// prueba sobre un objeto
Item item=jp.readValueAs(Item.class);
log.error(" probando " + item.toString() );

}
} else {
System.out.println("Error: records should be an array: skipping.");
jp.skipChildren();
}
} else {
System.out.println("Unprocessed property: " + fieldName);
jp.skipChildren();
}
}
jp.close(); // ensure resources get cleaned up timely and properly  
....

La clase Item sería:

public class Item implements Serializable {
private Long id;
private Long tipo;
private Long cantidad;

public Long getId() {
return id;
}

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

public Long getTipo() {
return tipo;
}

public void setTipo(Long valor) {
this.tipo = valor;
}

public Long getCantidad() {
return cantidad;
}

public void setCantidad(Long valor) {
this.cantidad = valor;
}

@Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
hash += (tipo != null ? tipo.hashCode() : 0);
return hash;
}

@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
  if (!(object instanceof Item)) {
return false;
}
  Item other = (Item) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}

@Override
public String toString() {
  return "com.jpa.Item[ id=" + id + " ]";
}

}


Referencias:

http://outerthought.org/blog/415-ot.html