2010-03-13 22 views
7

Vorrei sapere se esiste una pagina Web/software in grado di "tradurre" un oggetto Json feed in un oggetto Java con attributi.JSON feed to Java Object

Ad esempio:

{ 
      'firstName': 'John', 
      'lastName': 'Smith', 
      'address': { 
       'streetAddress': '21 2nd Street', 
       'city': 'New York' 
      } 
     } 

diventerebbero:

class Person { 
    private String firstName; 
    private String lastName; 
    private Address address; 

    public String getFirstName() { return firstName; } 
    public String getLastName() { return lastName; } 
    public Address getAddress() { return address; } 

    public void setFirstName(String firstName) { this.firstName = firstName; } 
    public void setLastName(String lastName) { this.lastName = lastName; } 
    public void setAddress(Address address) { this.address = address; } 

    public String toString() { 
     return String.format("firstName: %s, lastName: %s, address: [%s]", firstName, lastName, address); 
    } 
} 

class Address { 
    private String streetAddress; 
    private String city; 

    public String getStreetAddress() { return streetAddress; } 
    public String getCity() { return city; } 

    public void setStreetAddress(String streetAddress) { this.streetAddress = streetAddress; } 
    public void setCity(String city) { this.city = city; } 

    public String toString() { 
     return String.format("streetAddress: %s, city: %s", streetAddress, city); 
    } 
} 

Non sto chiedendo che perché sono pigro, ma il JSON vorrei analizzare ha un bel po 'di attributi .

risposta

1

Si potrebbe volere dare un'occhiata a Gson, la libreria Java JSON di Google. Ha metodi per serializzare oggetti da Java a JSON e deserializzare da oggetti JSON a Java.

Non l'ho mai usato per la deserializzazione, quindi non posso fornire molti dettagli su questo, per esempio come gestirà l'oggetto nidificato (indirizzo) ma immagino che sia in grado di gestirlo.

la documentazione delle API: http://google-gson.googlecode.com/svn/tags/1.3/docs/javadocs/index.html Il manuale d'uso: https://sites.google.com/site/gson/gson-user-guide

Buona fortuna!

2

Ho utilizzato con successo json-lib per serializzazione json e deserializzazione. Il vostro esempio sarà simile a questa:

String json = "{'firstName': 'John', 'lastName': 'Smith', 'address': {'streetAddress': '21 2nd Street', 'city': 'New York'}}"; 
JSONObject jsonObject = JSONObject.fromObject(json); 
Person bean = (Person) JSONObject.toBean(jsonObject, Person.class); 
System.out.println(bean); 

e stampe

firstName: John, lastName: Smith, address: [streetAddress: 21 2nd Street, city: New York] 

Se è necessario personalizzare ci sono un sacco di ganci di estensione. Nella mia applicazione ho aggiunto il supporto per serializzare una Locale su una stringa "sv_SE" piuttosto che un oggetto. E per deserializzare la stessa stringa su un oggetto Locale.