今天有个需求是,根据不同的数据格式展示不同的内容,兼容改版后的历史数据。我们直接展示TextView控件加载list集合,下面直接上代码。
数据格式如下:
[
{
"textkey": "测试key1",
"textValue": "测试value1"
},
{
"textkey": "测试key2",
"textValue": "测试value2"
},
{
"textkey": "测试key3",
"textValue": "测试value3"
}
]
我们要把数据展示到TextView上面,1.获取数据然后进行转换,2.数据拼接,3.展示。
1.新建实体类进行转换
public class TextBean {
private String textkey;
private String textValue;
public String getTextkey() {
return textkey == null ? "" : textkey;
}
public void setTextkey(String textkey) {
this.textkey = textkey == null ? "" : textkey;
}
public String getTextValue() {
return textValue == null ? "" : textValue;
}
public void setTextValue(String textValue) {
this.textValue = textValue == null ? "" : textValue;
}
}
2.格式化数据,然后拼接字符串
List<TextBean> List = new ArrayList<>();
String str = "";
List = JsonUtils.jsonToList(text, TextBean.class);//获取数据进行格式化处理
for (int i = 0; i < List.size(); i++) {
str = bz_beizhuStr + List.get(i).getTextkey() + ":" + List.get(i).getTextValue() + ";" + "\n";
}
//相对应的textView加载拼接好的字符串
textTest.set(str);
3.json工具方法
public final class JsonUtils {
/**
* Json文件转list数组
*
* @param jsonString:返回的串
* @param clazz:转换的类型
* @param <T>:泛型
* @return :返回值
*/
public static <T> List<T> jsonToList(String jsonString, Class<T> clazz) {
@SuppressWarnings("unchecked")
List<T> ts = (List<T>) com.alibaba.fastjson.JSONArray.parseArray(jsonString, clazz);
return ts;
}
}
到此代码写完了,希望能够帮助需要的童鞋。转载请标明出处!