如何从Json字符串解析Json数组

时间:2019-03-24 12:08:39

标签: java json gson

这是我的输入

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";

我检查了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);

但我为空

3 个答案:

答案 0 :(得分:1)

不明白您要做什么。

据我了解,MyClass应该具有getter和setter函数  喜欢

 public void setGeneration (String generation ) {
    this.generation = generation ;
}

public String getGeneration () {
    return generation ;
}

然后致电Gson

Gson gson = new GsonBuilder().create();
Myclass myclass= gson.fromJson(json, Myclass.class);

答案 1 :(得分:1)

您的Json不代表您要反序列化的类。

{  
   "myKey":[  
      {  
         "myHhome":"home1",
         "myAddress":"add",
         "dateTimeStamp":"Wed, 20 Mar 2019 14:38:54 GMT"
      }
   ],
   "basedata":{  
      "mydata":{  
         "mytype":"m1",
         "mytype2":"m2"
      }
   }
}

第二, .fromJson 用于反序列化,因此返回值必须是结果类。

Myclass myclass= GSON1.fromJson(json, Myclass.class);

对于您提供的Json,您还需要2个课程:

  • MyKey
  • 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
    }
    

我希望它可以帮助您了解如何通过Json表示类。

答案 2 :(得分:1)

如果只想获取json对象的值,请考虑使用其他库,例如org.jsonJackson

使用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);