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...
15 answers
Utilizzando org.libreria json:
JSONObject jsonObj = new JSONObject("{\"phonetype\":\"N95\",\"cat\":\"WP\"}");
A chiunque stia ancora cercando una risposta:
JSONParser parser = new JSONParser();
JSONObject json = (JSONObject) parser.parse(stringToParse);
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:
Ci sono vari serializzatori e deserializzatori Java JSON collegati dalla home page JSON.
Al momento della stesura di questo articolo, ci sono questi 20:
- org.json
- org.json.me
- Il nostro sito utilizza cookie tecnici e di terze parti.]}
- Json-lib
- Strumenti JSON
- Per maggiori informazioni clicca qui]}
- Stringtree
- SOJO
- Restlet
- Gettone
- json-taglib
- XStream
- JsonMarshaller
- Flexjson
- Strumenti JON
-
Per maggiori informazioni:
]} - Argo
- Perno
- jsonij
- fastjson
...ma naturalmente la lista può cambiare.
Soluzione Java 7
import javax.json.*;
...
String TEXT;
JsonObject body = Json.createReader(new StringReader(TEXT)).readObject()
;
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.
È necessario importare l'organizzazione.json
JSONObject jsonObj = null;
try {
jsonObj = new JSONObject("{\"phonetype\":\"N95\",\"cat\":\"WP\"}");
} catch (JSONException e) {
e.printStackTrace();
}
Per convertire String
in JSONObject
devi solo passare l'istanza String
nel Costruttore di JSONObject
.
Ad esempio:
JSONObject jsonObj = new JSONObject("your string");
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.
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"}
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);
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
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.
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(
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.