Come convertire jsonString in JSONObject in Java


Ho una variabile Stringa chiamata jsonString:

{"phonetype":"N95","cat":"WP"}

Ora voglio convertirlo in Oggetto JSON. Ho cercato di più su Google ma non ho ottenuto risposte attese...

Author: Raj Rajeshwar Singh Rathore, 2011-03-09

15 answers

Utilizzando org.libreria json:

JSONObject jsonObj = new JSONObject("{\"phonetype\":\"N95\",\"cat\":\"WP\"}");
 523
Author: dogbane, 2018-01-16 10:42:46

A chiunque stia ancora cercando una risposta:

JSONParser parser = new JSONParser();
JSONObject json = (JSONObject) parser.parse(stringToParse);
 119
Author: Mappan, 2014-09-30 01:01:02

Puoi usare google-gson. Dettagli:

Esempi di oggetti

class BagOfPrimitives {
  private int value1 = 1;
  private String value2 = "abc";
  private transient int value3 = 3;
  BagOfPrimitives() {
    // no-args constructor
  }
}

(Serializzazione)

BagOfPrimitives obj = new BagOfPrimitives();
Gson gson = new Gson();
String json = gson.toJson(obj); 
==> json is {"value1":1,"value2":"abc"}

Si noti che non è possibile serializzare oggetti con riferimenti circolari poiché ciò comporterà una ricorsione infinita.

(Deserializzazione)

BagOfPrimitives obj2 = gson.fromJson(json, BagOfPrimitives.class);  
==> obj2 is just like obj

Un altro esempio per Gson:

Gson è facile da imparare e implementare, è necessario sapere è i seguenti due metodi:

- > toJson () – converti oggetto java in Formato JSON

- > fromJson () - convertire JSON in oggetto java

import com.google.gson.Gson;

public class TestObjectToJson {
  private int data1 = 100;
  private String data2 = "hello";

  public static void main(String[] args) {
      TestObjectToJson obj = new TestObjectToJson();
      Gson gson = new Gson();

      //convert java object to JSON format
      String json = gson.toJson(obj);

      System.out.println(json);
  }

}

Uscita

{"data1":100,"data2":"hello"}

Risorse:

Home Page del progetto Google Gson

Guida utente Gson

Esempio

 39
Author: kamaci, 2011-03-09 13:16:14

Ci sono vari serializzatori e deserializzatori Java JSON collegati dalla home page JSON.

Al momento della stesura di questo articolo, ci sono questi 20:

...ma naturalmente la lista può cambiare.

 28
Author: T.J. Crowder, 2012-05-20 13:34:29

Soluzione Java 7

import javax.json.*;

...

String TEXT;
JsonObject body = Json.createReader(new StringReader(TEXT)).readObject()

;

 22
Author: RSG, 2015-03-23 17:48:05

Mi piace usare google-gson per questo, ed è proprio perché non ho bisogno di lavorare direttamente con JSONObject.

In tal caso avrei una classe che corrisponderà alle proprietà del tuo Oggetto JSON

class Phone {
 public String phonetype;
 public String cat;
}


...
String jsonString = "{\"phonetype\":\"N95\",\"cat\":\"WP\"}";
Gson gson = new Gson();
Phone fooFromJson = gson.fromJson(jsonString, Phone.class);
...

Tuttavia, penso che la tua domanda sia più simile, Come faccio a finire con un oggetto JSONObject reale da una stringa JSON.

Stavo guardando l'api google-json e non sono riuscito a trovare nulla di così semplice come org.l'api di json che è probabilmente quello che vuoi essere usando se hai così tanto bisogno di usare un barebone JSONObject.

Http://www.json.org/javadoc/org/json/JSONObject.html

Con org.json.JSONObject (un'altra API completamente diversa) Se vuoi fare qualcosa di simile...

JSONObject jsonObject = new JSONObject("{\"phonetype\":\"N95\",\"cat\":\"WP\"}");
System.out.println(jsonObject.getString("phonetype"));

Penso che la bellezza di google-gson sia che non è necessario gestire JSONObject. Basta afferrare json, passare la classe a voler deserializzare in, e gli attributi della classe saranno abbinati al JSON, ma poi di nuovo, tutti ha le proprie esigenze, forse non puoi permetterti il lusso di avere classi pre-mappate sul lato della deserializzazione perché le cose potrebbero essere troppo dinamiche sul lato della generazione di JSON. In tal caso basta usare json.org.

 9
Author: Gubatron, 2011-03-09 13:23:36

È necessario importare l'organizzazione.json

JSONObject jsonObj = null;
        try {
            jsonObj = new JSONObject("{\"phonetype\":\"N95\",\"cat\":\"WP\"}");
        } catch (JSONException e) {
            e.printStackTrace();
        }
 8
Author: Cabezas, 2014-09-11 10:21:30

Per convertire String in JSONObject devi solo passare l'istanza String nel Costruttore di JSONObject.

Ad esempio:

JSONObject jsonObj = new JSONObject("your string");
 8
Author: Charu, 2016-12-20 04:31:23

Se si utilizza http://json-lib.sourceforge.net (Net.SF.json.JSONObject)

È abbastanza facile:

String myJsonString;
JSONObject json = JSONObject.fromObject(myJsonString);

O

JSONObject json = JSONSerializer.toJSON(myJsonString);

Ottieni i valori quindi con json.getString (param), json.getInt (param) e così via.

 3
Author: Thero, 2013-04-03 11:07:36

Usa JsonNode di fasterxml per l'analisi Json generica. Crea internamente una mappa del valore chiave per tutti gli input.

Esempio:

private void test(@RequestBody JsonNode node)

Stringa di input:

{"a":"b","c":"d"}
 3
Author: Vishnu, 2016-09-08 14:05:59

Per convertire una stringa in json e la puntura è come json. {"phonetype": "N95", "cat": "WP"}

String Data=response.getEntity().getText().toString(); // reading the string value 
JSONObject json = (JSONObject) new JSONParser().parse(Data);
String x=(String) json.get("phonetype");
System.out.println("Check Data"+x);
String y=(String) json.get("cat");
System.out.println("Check Data"+y);
 2
Author: Aravind Cheekkallur, 2013-10-10 05:49:54

Per impostare json oggetto singolo alla lista ie

"locations":{

}

In a List<Location>

Utilizzare

ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationConfig.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);

Jackson.mapper-asl-1.9.7.vaso

 0
Author: user3012570, 2014-01-06 13:22:10

SI noti che GSON con la deserializzazione di un'interfaccia comporterà un'eccezione come di seguito.

"java.lang.RuntimeException: Unable to invoke no-args constructor for interface XXX. Register an InstanceCreator with Gson for this type may fix this problem."

Mentre deserialize; GSON non sa quale oggetto deve essere intantiato per quell'interfaccia.

Questo è risolto in qualche modo qui.

Tuttavia FlexJSON ha questa soluzione intrinsecamente. mentre serializza il tempo, aggiunge il nome della classe come parte di json come di seguito.

{
    "HTTPStatus": "OK",
    "class": "com.XXX.YYY.HTTPViewResponse",
    "code": null,
    "outputContext": {
        "class": "com.XXX.YYY.ZZZ.OutputSuccessContext",
        "eligible": true
    }
}

Quindi JSON sarà cumber alcuni; ma non è necessario scrivere InstanceCreator che è richiesto in GSON.

 0
Author: Kanagavelu Sugumar, 2017-05-23 11:47:29

Non è necessario utilizzare alcuna libreria esterna.

Puoi invece usare questa classe:) (gestisce anche elenchi, elenchi nidificati e json)

public class Utility {

    public static Map<String, Object> jsonToMap(Object json) throws JSONException {

        if(json instanceof JSONObject)
            return _jsonToMap_((JSONObject)json) ;

        else if (json instanceof String)
        {
            JSONObject jsonObject = new JSONObject((String)json) ;
            return _jsonToMap_(jsonObject) ;
        }
        return null ;
    }


   private static Map<String, Object> _jsonToMap_(JSONObject json) throws JSONException {
        Map<String, Object> retMap = new HashMap<String, Object>();

        if(json != JSONObject.NULL) {
            retMap = toMap(json);
        }
        return retMap;
    }


    private static Map<String, Object> toMap(JSONObject object) throws JSONException {
        Map<String, Object> map = new HashMap<String, Object>();

        Iterator<String> keysItr = object.keys();
        while(keysItr.hasNext()) {
            String key = keysItr.next();
            Object value = object.get(key);

            if(value instanceof JSONArray) {
                value = toList((JSONArray) value);
            }

            else if(value instanceof JSONObject) {
                value = toMap((JSONObject) value);
            }
            map.put(key, value);
        }
        return map;
    }


    public static List<Object> toList(JSONArray array) throws JSONException {
        List<Object> list = new ArrayList<Object>();
        for(int i = 0; i < array.length(); i++) {
            Object value = array.get(i);
            if(value instanceof JSONArray) {
                value = toList((JSONArray) value);
            }

            else if(value instanceof JSONObject) {
                value = toMap((JSONObject) value);
            }
            list.add(value);
        }
        return list;
    }
}

Per convertire la tua stringa JSON in hashmap usa questo:

HashMap<String, Object> hashMap = new HashMap<>(Utility.jsonToMap(
 0
Author: Natesh bhat, 2018-07-01 07:59:31

Meglio andare con un modo più semplice usando org.json lib. Basta fare un approccio molto semplice come di seguito:

JSONObject obj = new JSONObject();
obj.put("phonetype", "N95");
obj.put("cat", "WP");

Ora obj è la tua forma JSONObject convertita della tua rispettiva stringa. Questo è nel caso in cui tu abbia coppie nome-valore.

Per una stringa puoi passare direttamente al costruttore di JSONObject. Se sarà un json String valido, allora va bene altrimenti genererà un'eccezione.

 -1
Author: TheLittleNaruto, 2014-11-11 12:58:55