[英]How to parse Json array from Json string
This is my input这是我的输入
String str ="{\n" +
" \"myKey\": [{\n" +
" \"myHhome\": \"home1\",\n" +
" \"myAddress\": \"add\",\n" +
" \"dateTimeStamp\": \"Wed, 20 Mar 2019 14:38:54 GMT\"\n" +
" }\n" +
" ],\n" +
" \"basedata\": {\n" +
" \"mydata\": {\n" +
" \"mytype\": \"m1\",\n" +
" \"mytype2\": \"m2\"\n" +
" }\n" +
" }\n" +
"}\n";
I chekced the json and it is valid I want to use GSON to get the value of the myHhome ( in my case hom1)我检查了 json 并且它是有效的我想使用 GSON 来获取 myHhome 的值(在我的情况下为 hom1)
static class Myclass{
public String generation = null;
}
final Gson GSON1 = new Gson();
String result= GSON1.fromJson(str,Myclass.class);
System.out.println(result);
but i got null但我得到了空
Don't understand what you trying to do.不明白你想做什么。
As I understand MyClass should have getter and setter function Like据我了解 MyClass 应该有 getter 和 setter 函数像
public void setGeneration (String generation ) {
this.generation = generation ;
}
public String getGeneration () {
return generation ;
}
And call Gson并调用 Gson
Gson gson = new GsonBuilder().create();
Myclass myclass= gson.fromJson(json, Myclass.class);
Your Json does not represents the class you are trying to deserialize it to.您的 Json 不代表您尝试将其反序列化为的类。
{
"myKey":[
{
"myHhome":"home1",
"myAddress":"add",
"dateTimeStamp":"Wed, 20 Mar 2019 14:38:54 GMT"
}
],
"basedata":{
"mydata":{
"mytype":"m1",
"mytype2":"m2"
}
}
}
Second, .fromJson is used to deserialization so the return must be the resultant Class.其次, .fromJson用于反序列化,因此返回必须是结果类。
Myclass myclass= GSON1.fromJson(json, Myclass.class);
For the Json you provided you need 2 more classes:对于您提供的 Json,您还需要 2 个类:
MyData我的数据
class Myclass { public List<MyKey> myKey = null; public Basedata basedata = null; // getters and setters } class Basedata { private MyData mydata; // getters and setters } class MyData { private String mytype; private String mytype2; // getters and setters } class MyKey { public String myHhome; public String myAddress; public String dateTimeStamp; // getters and setters }
I hope it helps you to understand how classes are represented though Json.我希望它能帮助你理解类是如何通过 Json 表示的。
If you only want to get the value of a json object, consider using a different library such as org.json or Jackson .如果您只想获取 json 对象的值,请考虑使用不同的库,例如org.json或Jackson 。
Using org.json:使用 org.json:
JSONObject json = new JSONObject("your JSON string here"); // Parse the JSON
JSONArray array = json.getJSONArray("myKey"); // Get the JSON array represented by the key "myKey"
JSONObject home = array.getJSONObject(0); // Get the element at index 0 as a JSONObject
String result = home.getString("myHhome"); // Get the string represented by the key "myHhome"
System.out.println(result);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.