2013-08-27 7 views
0

je la chaîne JSON suivante:Java analyse syntaxique JSON dans flotteurs

String json = {"z":4.78944,"y":-0.07604187,"x":11.841576}; 

je voudrais analyser et créer:

float x = 4.78944; 
float y = -0.07604187; 
float z = 11.841576; 

Comment puis-je arriver en Java avec l'entrée variable String json ?

+1

tout d'abord, cette affectation de chaîne ne compilera pas. Deuxièmement, avez-vous fait des efforts pour rechercher certaines des bibliothèques d'analyse JSON les plus courantes comme Gson et Jackson? – AdamSpurgin

Répondre

1

Si vous souhaitez une désérialisation orientée objet, consultez Google-Gson here.

Créer un modèle Coordonate.java:

public class Coordonate { 
    private float x; 
    private float y; 
    private float z; 

    public float getX() { return x; } 
    public float getY() { return y; } 
    public float getZ() { return z; } 
} 

deserialize votre chaîne JSON:

String json = "{\"z\":4.78944,\"y\":-0.07604187,\"x\":11.841576}"; 
Coordonate cord = new Gson().fromJson(json, Coordonate.class); 
1

utilisation JSONObject: http://www.json.org/javadoc/org/json/JSONObject.html

Par la suite, utiliser la fonction getDouble pour accéder à la valeur double des touches x, y et z.

+1

Cela vous semble-t-il exact? 'float x = (flottant) json.getDouble (" x ");' Il compile, pas sûr que cela fonctionnera. – JDS

+0

@JDS - L'avez-vous essayé? –

+0

Il devrait. J'ai déjà utilisé JSONObject pour désérialiser une chaîne JSON valide, puis accéder aux attributs. – Vivek