【问题标题】:Can i get the name of the json object from same json object in kotlin? [closed]我可以从 kotlin 中的同一个 json 对象获取 json 对象的名称吗? [关闭]
【发布时间】:2021-04-19 14:13:58
【问题描述】:

我尝试使用 json 对象更新 sharePreference 值。 首先,我创建带有名称的 json 对象,然后更新 sharedPreference 中的对象。 但是,我无法获取 json 对象名称。请帮帮我。

 team1.put("name", "India")
 updateData(team1)

 private fun updateData(data: JSONObject) {
    val sharedPref: SharedPreferences = getSharedPreferences("SharedPref1", 0)
    val editor:SharedPreferences.Editor =  sharedPref.edit()
    editor.putString("JSONObjectName",data.toString()) // How to get the JSONObject name?

} 

我想要这个,data.name == team1

【问题讨论】:

    标签: android json kotlin


    【解决方案1】:

    参考您的代码,您正在寻找名为“名称”的属性。对吧?

    你必须这样做:

    private fun updateData(data: JSONObject) {
    
        val name = data.getString("name")
    
        val sharedPref: SharedPreferences = getSharedPreferences("SharedPref1", 0)
        val editor:SharedPreferences.Editor =  sharedPref.edit()
    
        editor.putString("JSONObjectName", name)
    }
    

    在访问 JSONObject 之前不要忘记检查它是否包含名为“name”的属性以避免崩溃;)

    【讨论】:

      猜你喜欢
      • 2021-11-26
      • 1970-01-01
      • 2013-01-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-26
      • 1970-01-01
      相关资源
      最近更新 更多