Conversione dei dati JSON in oggetto Java


Voglio essere in grado di accedere alle proprietà da una stringa JSON all'interno del mio metodo di azione Java. La stringa è disponibile semplicemente dicendo myJsonString = object.getJson(). Di seguito è riportato un esempio di come può apparire la stringa:

{
    '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 matrice di altri oggetti JSON. L'intenzione è di estrarre un elenco di ID in cui un determinato oggetto possiede una proprietà group che contiene altri oggetti JSON. Ho guardato Gson di Google come un potenziale plugin JSON. Qualcuno può offrire una qualche forma di guida su come posso generare Java da questa stringa JSON?

Author: nabster, 2009-11-06

12 answers

Ho guardato Gson di Google come un potenziale plugin JSON. Qualcuno può offrire qualche forma di guida su come posso generare Java da questa stringa JSON?

Google Gson supporta generici e fagioli nidificati. Il [] in JSON rappresenta un array e dovrebbe essere associato a una raccolta Java come List o solo un semplice array Java. Il {} in JSON rappresenta un oggetto e dovrebbe mappare a un Java Map o solo qualche JavaBean classe.

Si dispone di un oggetto JSON con diverse proprietà di cui la proprietà groups rappresenta un array di oggetti nidificati dello stesso tipo. Questo può essere analizzato con Gson nel modo seguente:

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 adatto e chiamare Gson#fromJson().

Vedi anche:

 341
Author: BalusC, 2020-06-20 09:12:55

Bewaaaaare di Gson! È molto bello, molto grande, ma nel momento in cui vuoi fare qualcosa di diverso da oggetti semplici, potresti facilmente aver bisogno di iniziare a costruire i tuoi serializzatori (che non è che difficile).

Inoltre, se hai una matrice di Oggetti e deserializzi alcuni json in quella matrice di Oggetti, i veri tipi vengono persi! Gli oggetti completi non saranno nemmeno copiati! Usa XStream.. Che, se si utilizza jsondriver e si impostano le impostazioni corrette, codificherà i tipi brutti nel json effettivo, 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 di GSON.

 47
Author: Jor, 2013-01-22 18:43:21

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

Qui ci sono più buone scelte:

  • Jackson (Github ) powerful potente associazione dati (JSON a / da POJO), streaming (ultra veloce), modello ad albero (conveniente per l'accesso non tipizzato)
  • Flex-JSON highly serializzazione altamente configurabile

MODIFICA (agosto/2013):

Un altro da considerare:

  • Genson functionality funzionalità simile a Jackson, mirato ad essere più facile da configurare da parte dello sviluppatore
 26
Author: StaxMan, 2015-02-25 11:12:50

O con Jackson:

String json = "...
ObjectMapper m = new ObjectMapper();
Set<Product> products = m.readValue(json, new TypeReference<Set<Product>>() {});
 17
Author: Gene De Lisa, 2011-06-22 16:15:11

Se, con qualsiasi modifica, ci si trova in un'applicazione che utilizza già http://restfb.com / allora puoi fare:

import com.restfb.json.JsonObject;

...

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

Ecc.

 7
Author: cherouvim, 2011-03-31 13:13:44

Codice java semplice e funzionante per convertire JSONObject in Java Object

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

}

Carico da Json.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());

    }
}
 5
Author: Rahul Raina, 2016-04-27 07:25:21
HashMap keyArrayList = new HashMap();
Iterator itr = yourJson.keys();
while (itr.hasNext())
{
    String key = (String) itr.next();
    keyArrayList.put(key, yourJson.get(key).toString());
}
 5
Author: HEAT, 2019-06-11 16:42:07

Se si utilizza qualsiasi tipo di mappe speciali con chiavi o valori anche di mappe speciali, troverete che non è contemplato dall'implementazione di Google.

 3
Author: Juanma, 2010-04-23 21:36:15

Cosa c'è di sbagliato nella roba standard?

JSONObject jsonObject = new JSONObject(someJsonString);
JSONArray jsonArray = jsonObject.getJSONArray("someJsonArray");
String value = jsonArray.optJSONObject(i).getString("someJsonValue");
 2
Author: Kevin, 2013-10-23 14:06:06

Prova boon:

Https://github.com/RichardHightower/boon

È malvagio veloce:

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

Non credermi sulla parola... controlla il benchmark gatling.

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

(Fino a 4x è alcuni casi, e fuori dei 100s di test. Ha anche una modalità di sovrapposizione indice che è ancora più veloce. È giovane ma ne ha già internauti.)

Può analizzare JSON in Mappe ed elenchi più velocemente di qualsiasi altra lib può analizzare in un DOM JSON e cioè senza la modalità di sovrapposizione dell'indice. Con la modalità Overlay Boon Index, è ancora più veloce.

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

Ha anche la modalità JSON in JavaBean più veloce.

Nuovo, ma se la velocità e l'API semplice è quello che stai cercando, Non penso che ci sia un'API più veloce o più minimalista.

 0
Author: RickHigh, 2013-12-14 07:38:26

Il modo più semplice è che puoi usare questo metodo softconvertvalue che è un metodo personalizzato in cui puoi convertire jsonData nella tua specifica classe 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);
}
 0
Author: Dipen Chawla, 2019-06-11 16:41:19

A seconda del formato JSON di input (stringa/file) creare un jSONString. Esempio oggetto classe messaggio corrispondente a JSON può essere ottenuto come di seguito:

Message msgFromJSON = new ObjectMapper().readValue(jSONString, Message.class);
 0
Author: Shailendra Singh, 2020-08-11 13:03:20