Domanda

Voglio essere in grado di accedere a oggetti di una stringa JSON nel mio metodo di azione Java. La stringa è disponibile semplicemente dicendo myJsonString = object.getJson(). Di seguito è riportato un esempio di ciò che la stringa può apparire come:

{
    'title': 'ComputingandInformationsystems',
    'id': 1,
    'children': 'true',
    'groups': [{
        'title': 'LeveloneCIS',
        'id': 2,
        'children': 'true',
        'groups': [{
            'title': 'IntroToComputingandInternet',
            'id': 3,
            'children': 'false',
            'groups': []
        }]
    }]
}

In questa stringa ogni oggetto JSON contiene una serie di altri oggetti JSON. L'intento è quello di estrarre un elenco di ID in cui qualsiasi oggetto che possiedono una proprietà del gruppo che contiene altri oggetti JSON. Ho guardato GSON di Google come un potenziale plug-in JSON. Chiunque può offrire qualche forma di indicazioni sul come posso generare Java da questa stringa JSON?

È stato utile?

Soluzione

  

Ho guardato GSON di Google come un potenziale plug-in JSON. Chiunque può offrire qualche forma di indicazioni sul come posso generare Java da questa stringa JSON?

Google GSON supporta farmaci generici e fagioli nidificate. Il [] in JSON rappresenta un array e dovrebbe mappare una collezione Java come List o semplicemente un array di Java pianura. Il {} in JSON rappresenta un oggetto e dovrebbe mappare una rel="noreferrer"> Java Map o solo qualche classe JavaBean.

Hai un oggetto JSON con diverse proprietà di cui la struttura groups rappresenta un array di oggetti nidificati allo stesso tipo. Questo può essere analizzato con GSON seguente modo:

package com.stackoverflow.q1688099;

import java.util.List;
import com.google.gson.Gson;

public class Test {

    public static void main(String... args) throws Exception {
        String json = 
            "{"
                + "'title': 'Computing and Information systems',"
                + "'id' : 1,"
                + "'children' : 'true',"
                + "'groups' : [{"
                    + "'title' : 'Level one CIS',"
                    + "'id' : 2,"
                    + "'children' : 'true',"
                    + "'groups' : [{"
                        + "'title' : 'Intro To Computing and Internet',"
                        + "'id' : 3,"
                        + "'children': 'false',"
                        + "'groups':[]"
                    + "}]" 
                + "}]"
            + "}";

        // Now do the magic.
        Data data = new Gson().fromJson(json, Data.class);

        // Show it.
        System.out.println(data);
    }

}

class Data {
    private String title;
    private Long id;
    private Boolean children;
    private List<Data> groups;

    public String getTitle() { return title; }
    public Long getId() { return id; }
    public Boolean getChildren() { return children; }
    public List<Data> getGroups() { return groups; }

    public void setTitle(String title) { this.title = title; }
    public void setId(Long id) { this.id = id; }
    public void setChildren(Boolean children) { this.children = children; }
    public void setGroups(List<Data> groups) { this.groups = groups; }

    public String toString() {
        return String.format("title:%s,id:%d,children:%s,groups:%s", title, id, children, groups);
    }
}

abbastanza semplice, non è vero? Basta avere un JavaBean adeguato e chiamare Gson#fromJson() .

Vedi anche:

Altri suggerimenti

Bewaaaaare di GSON! E 'molto fresco, molto grande, ma la seconda si vuole fare qualcosa di diverso da semplici oggetti, si potrebbe facilmente essere necessario per iniziare a costruire il proprio serializzatori (che non è che difficile).

Inoltre, se si dispone di una serie di oggetti, e si deserializzare alcuni JSON in quella serie di oggetti, i veri tipi sono persi! Gli oggetti completi non sarà nemmeno essere copiati! Usa XStream .. che, se si utilizza il jsondriver e impostando le impostazioni corrette, codificherà tipi brutti in JSON reale, in modo da non perdere nulla. Un piccolo prezzo da pagare (brutto JSON) per la vera serializzazione.

Si noti che Jackson risolve questi problemi, ed è più veloce rispetto GSON.

Stranamente, l'unico processore JSON decente menzionato finora è stato GSON.

Qui ci sono più buone scelte:

  • Jackson Github ) - dati potenti binding (JSON da / per POJO), streaming (ultra veloce), modello di albero (comodo per l'accesso non tipizzato)
  • Flex-JSON - serializzazione altamente configurabile

EDIT (Ago / 2013):

Una più da considerare:

  • Genson - una funzionalità simile a Jackson, l'obiettivo di essere più facile da configurare dallo sviluppatore

O con Jackson:

String json = "...
ObjectMapper m = new ObjectMapper();
Set<Product> products = m.readValue(json, new TypeReference<Set<Product>>() {});

Se, per qualsiasi cambiamento, ci si trova in un'applicazione che utilizza già http://restfb.com/ poi si può fare:

import com.restfb.json.JsonObject;

...

JsonObject json = new JsonObject(jsonString);
json.get("title");

ecc.

Se si utilizza qualsiasi tipo di mappe speciali con chiavi o valori anche di mappe speciali, troverete che non è contemplato dalla realizzazione di google.

Facile e lavorare codice Java per convertire JSONObject a Java Object

Employee.java

import java.util.HashMap;
import java.util.Map;

import javax.annotation.Generated;

import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;

@JsonInclude(JsonInclude.Include.NON_NULL)
@Generated("org.jsonschema2pojo")
@JsonPropertyOrder({
"id",
"firstName",
"lastName"
})
public class Employee {

@JsonProperty("id")
private Integer id;
@JsonProperty("firstName")
private String firstName;
@JsonProperty("lastName")
private String lastName;
@JsonIgnore
private Map<String, Object> additionalProperties = new HashMap<String, Object>();

/**
*
* @return
* The id
*/
@JsonProperty("id")
public Integer getId() {
return id;
}

/**
*
* @param id
* The id
*/
@JsonProperty("id")
public void setId(Integer id) {
this.id = id;
}

/**
*
* @return
* The firstName
*/
@JsonProperty("firstName")
public String getFirstName() {
return firstName;
}

/**
*
* @param firstName
* The firstName
*/
@JsonProperty("firstName")
public void setFirstName(String firstName) {
this.firstName = firstName;
}

/**
*
* @return
* The lastName
*/
@JsonProperty("lastName")
public String getLastName() {
return lastName;
}

/**
*
* @param lastName
* The lastName
*/
@JsonProperty("lastName")
public void setLastName(String lastName) {
this.lastName = lastName;
}

@JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}

@JsonAnySetter
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}

}

LoadFromJSON.java

import org.codehaus.jettison.json.JSONObject;

import com.fasterxml.jackson.databind.ObjectMapper;

public class LoadFromJSON {

    public static void main(String args[]) throws Exception {
        JSONObject json = new JSONObject();
        json.put("id", 2);
        json.put("firstName", "hello");
        json.put("lastName", "world");

        byte[] jsonData = json.toString().getBytes();

        ObjectMapper mapper = new ObjectMapper();
        Employee employee = mapper.readValue(jsonData, Employee.class);

        System.out.print(employee.getLastName());

    }
}
HashMap keyArrayList = new HashMap();
Iterator itr = yourJson.keys();
while (itr.hasNext())
{
    String key = (String) itr.next();
    keyArrayList.put(key, yourJson.get(key).toString());
}

Cosa c'è di sbagliato con le cose standard?

JSONObject jsonObject = new JSONObject(someJsonString);
JSONArray jsonArray = jsonObject.getJSONArray("someJsonArray");
String value = jsonArray.optJSONObject(i).getString("someJsonValue");

Dare manna una prova:

https://github.com/RichardHightower/boon

E 'cattivo digiuno:

https://github.com/RichardHightower/json-parsers-benchmark

Non prendere la mia parola per esso ... controllare il punto di riferimento gatling.

https://github.com/gatling/json-parsers-benchmark

(fino a 4x è alcuni casi, e fuori dei 100s di prova. Essa ha anche un modo dell'indice di sovrapposizione che è ancora più veloce. E 'giovane, ma ha già alcuni utenti.)

E 'possibile analizzare JSON per mappe ed elenchi più velocemente di qualsiasi altra lib grado di analizzare a un JSON DOM e che è senza la modalità Index Overlay. Con la modalità Boon Indice Overlay, è ancora più veloce.

Ha anche una modalità lassista JSON molto veloce e una modalità PLIST parser. :) (e ha una memoria super basso, diretto dalla modalità byte con codifica UTF-8 al volo).

Ha anche la più veloce per JSON modalità JavaBean troppo.

E 'nuovo, ma se la velocità e semplice API è quello che stai cercando, non credo che ci sia un API minimalista più veloce o più.

A seconda del formato JSON di ingresso (stringa / file) creare un jSONString. oggetto campione Classe messaggio corrispondente al JSON può essere ottenuta come segue:

Messaggio msgFromJSON = new ObjectMapper () readValue (jSONString, Message.class);.

Il modo più semplice è che è possibile utilizzare questo metodo softconvertvalue che è un metodo personalizzato in cui è possibile convertire jsonData nella vostra specifica classe di Dto.

Dto response = softConvertValue(jsonData, Dto.class);


public static <T> T softConvertValue(Object fromValue, Class<T> toValueType) 
{
    ObjectMapper objMapper = new ObjectMapper();
    return objMapper
        .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
        .convertValue(fromValue, toValueType);
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top