【问题标题】:How do I convert a JSONObject to class object?如何将 JSONObject 转换为类对象?
【发布时间】:2013-02-23 07:12:11
【问题描述】:

我需要为我的一个 android 项目使用 gson 库将 JSONObject 转换为 Location 对象。我不确定如何做到这一点。谁能帮我这个。提前致谢。

我有类似的代码

JSONArray input = new JSONArray(extras.getString("loc_json"));

我想将从 JSONArray 获取的 JSONObject 转换为 Location 类对象。我只是想知道是否有一个函数可以直接完成。

如果我以错误的方式提出问题,请原谅我。由于我没有得到direct函数,所以我是这样弄的。

 loc_temp = (Location) gson.fromJson(input.getJSONObject(i).toString(), Location.class);;

抱歉这个愚蠢的问题。

【问题讨论】:

    标签: android gson


    【解决方案1】:

    Here's a tutorial 代表 GSON - 我认为它应该有助于加深您的理解。本质上解析是这样完成的:

    String mJsonString = "...";
    JsonParser parser = new JsonParser(); 
    JsonElement mJson =  parser.parse(mJsonString);
    Gson gson = new Gson();
    MyDataObject object = gson.fromJson(mJson, MyDataObject.class);
    

    【讨论】:

    • 应该是“new JsonParser().parse(...)”.. 花了几分钟试图找出问题所在
    【解决方案2】:

    使用 com.google.gson.JsonObject & JsonArray 而不是 org.json.*

    像这样:

    Gson gson = new Gson();
    Type typeOfT = new TypeToken<List<Location.class>>(){}.getType();
    JsonParser parser = new JsonParser();
    JsonObject jo = (JsonObject) parser.parse(jsonStr);
    JsonArray ja = jo.getAsJsonArray("memberName");
    list = gson.fromJson(ja, typeOfT);
    

    【讨论】:

      【解决方案3】:

      如果你还想使用 org.json.JSONObject

      org.json.JSONObject o;
      ObjectMapper m = new ObjectMapper();
      MyClass myClass = m.readValue(o.toString(), MyClass.class);
      

      【讨论】:

      • 这里的 ObjectMapper 是什么..?
      • 我猜:com.fasterxml.jackson.databind.ObjectMapper
      • 它是如何连接到gson的?
      【解决方案4】:

      对于科特林

       val objType = object : TypeToken<MyClass>() {
      
          }.getType()
          var myclassObj = gson.fromJson(value,objType) 
      

       val objectResponse = Gson().fromJson(Gson().toJson(resp), MyClass::class.java)
      

      【讨论】:

        【解决方案5】:

        将 JSONObject 转换为 Model 类::

        val jsonObject = JSONObject(data[0].toString())
        val jsonModel = jsonObject.getJSONObject(KEY.message).toString()
        val chatModel = Gson().fromJson(model, ChatModel::class.java))
        

        【讨论】:

          猜你喜欢
          • 2014-08-10
          • 1970-01-01
          • 2017-12-27
          • 2016-05-14
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多