当前位置:Gxlcms > PHP教程 > Android如何用Gson把数据转换成List<Map<string,string>>

Android如何用Gson把数据转换成List<Map<string,string>>

时间:2021-07-01 10:21:17 帮助过:27人阅读

我现在有任意长度的json数据,用php的json_encode()生成,如下格式

[{"rowID":"1","Name":"tqtqwet","Comment":"qewrtqwe"},{"rowID":"2","Name":"waf","Comment":"agsadga"},{"rowID":"3","Name":"android","Comment":"fafdadsf"},{"rowID":"4","Name":"android222","Comment":"fasdfas"},{"rowID":"5","Name":"fadfa","Comment":"adgasd"}]

现在想用把它转换成List>的格式,并用listView显示出来。其中hashmap的第一个键对应“Name”,第二个键对应“Comment”,“rowID”无视掉。请问怎么能最快捷地完成这种转换?如果有办法可以绕过也可以!谢谢

回复内容:

我现在有任意长度的json数据,用php的json_encode()生成,如下格式

[{"rowID":"1","Name":"tqtqwet","Comment":"qewrtqwe"},{"rowID":"2","Name":"waf","Comment":"agsadga"},{"rowID":"3","Name":"android","Comment":"fafdadsf"},{"rowID":"4","Name":"android222","Comment":"fasdfas"},{"rowID":"5","Name":"fadfa","Comment":"adgasd"}]

现在想用把它转换成List>的格式,并用listView显示出来。其中hashmap的第一个键对应“Name”,第二个键对应“Comment”,“rowID”无视掉。请问怎么能最快捷地完成这种转换?如果有办法可以绕过也可以!谢谢

这个json数据格式很简单,不用你想象的那么复杂就能解析;
你需要一个JavaBean对象:
CustomClass.java:

    public class CustomClass {

     private String Name;
     private String Comment;

    public String getName() {
      return Name;
    }
    public void setName(String name) {
      Name = name;
    }
    public String getComment() {
      return Comment;
    }
    public void setComment(String comment) {
      Comment = comment;
    }
    }

MainActivity.java:

    public class MainActivity extends Activity {
    //你的json数据
    String jsonString="     [{\"rowID\":\"1\",\"Name\":\"tqtqwet\",\"Comment\":\"qewrtqwe\"},{\"rowID\":\"2\",\"Name\":\"waf\",\"Comment\":\"agsadga\"},{\"rowID\":\"3\",\"Name\":\"android\",\"Comment\":\"fafdadsf\"},{\"rowID\":\"4\",\"Name\":\"android222\",\"Comment\":\"fasdfas\"},{\"rowID\":\"5\",\"Name\":\"fadfa\",\"Comment\":\"adgasd\"}]";
        @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Type listType = new TypeToken>(){}.getType();
    ArrayList customList = new Gson().fromJson(jsonString, listType);
    }
    }

customList就是你想要的那个带有json数据的集合,你可以通过customList.get(index).getName() or getXXX()得到你想要的值

人气教程排行