J'ai une variable String appelée jsonString
:
{"phonetype":"N95","cat":"WP"}
Je veux maintenant la convertir en objet JSON. J’ai fait des recherches sur Google, mais je n’ai pas obtenu de réponses attendues...
Utilisation de la bibliothèque [org.json][1] :
try {
JSONObject jsonObject = new JSONObject("{\"phonetype\":\"N95\",\"cat\":\"WP\"}");
}catch (JSONException err){
Log.d("Error", err.toString());
}
Vous pouvez utiliser google-gson
. Détails :
Exemples d'objets
class BagOfPrimitives {
private int value1 = 1;
private String value2 = "abc";
private transient int value3 = 3;
BagOfPrimitives() {
// no-args constructor
}
}
(Sérialisation)
BagOfPrimitives obj = new BagOfPrimitives();
Gson gson = new Gson();
String json = gson.toJson(obj);
==> json is {"value1":1,"value2":"abc"}
Notez que vous ne pouvez pas sérialiser des objets avec des références circulaires car cela entraînerait une récursion infinie.
(Désérialisation)
BagOfPrimitives obj2 = gson.fromJson(json, BagOfPrimitives.class);
==> obj2 is just like obj
Un autre exemple pour Gson:
Gson est facile à apprendre et à mettre en œuvre, vous devez connaître les deux méthodes suivantes :
-> toJson() - convertit un objet java au format JSON
-fromJson() - convertit JSON en objet 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);
}
}
Sortie
{"data1":100,"data2":"hello"}
Resources:
[Page d'accueil du projet Google Gson][1]
[Guide de l'utilisateur Gson] [2]
[Exemple] [3]
[1] : http://code.google.com/p/google-gson/ [2] : http://sites.google.com/site/gson/gson-user-guide [3] : http://www.mkyong.com/java/how-do-convert-java-object-to-from-json-format-gson-api/
Il existe plusieurs sérialiseurs et désérialiseurs Java JSON liés à la [page d'accueil JSON][1].
Au moment où nous écrivons ces lignes, il y en a 22 :
...mais bien sûr la liste peut changer.
[1] : http://json.org