I have the following json string:
String json = {"z":4.78944,"y":-0.07604187,"x":11.841576};
I would like to parse it and create:
float x = 4.78944;
float y = -0.07604187;
float z = 11.841576;
How can I accomplish this in Java with the input variable String json
?
Use JSONObject: http://www.json.org/javadoc/org/json/JSONObject.html
Thereafter, use the getDouble function to access the double value of the keys x, y and z.
If you want an Object Model oriented deserialization, take a look at Google-Gson here .
Create a model 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 your JSON string:
String json = "{\"z\":4.78944,\"y\":-0.07604187,\"x\":11.841576}";
Coordonate cord = new Gson().fromJson(json, Coordonate.class);
You can also use a more powerful library than just the reference implementation and use Jackson . Look at this about how to use it in your usecase.
In addition to Vivec's answer using: http://www.json.org/javadoc/org/json/JSONObject.html
Although there is no getFloat()
on JSONObject getting it as a string and parsing it into float worked fine for me.:
Float.parseFloat(myJsonObject.getString("x"));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.