[英]Android-Java List to String and vice versa
I am new to Android programming and I wanted to create a function to take in a list and return a String.我是 Android 编程的新手,我想创建一个 function 来获取一个列表并返回一个字符串。 That's my code:
那是我的代码:
private String List_to_String(final ArrayList<String> list) {
String returnString = "{";
for (String _s : list) {
returnString = returnString + _s.replace(":","\\:") + ":";
}
if (returnString != null && returnString.length() > 0) {
returnString = returnString.substring(0,
returnString.length() - 1);
}
returnString = returnString.concat("}");
return returnString;
}
It works but now I want to make a function that returns a ArrayList when I give a String generated with the function above also I think you need to take extra care of the ":".它可以工作,但现在我想制作一个 function,当我给出一个由 function 生成的字符串时,它会返回一个 ArrayList,我认为你还需要特别注意上面的“:”。 So if I have a String
所以如果我有一个字符串
HDJDJJDJ:JSJSJSJJSJS:SJJSHS\:\:JS
the function should return a list with these items function 应返回包含这些项目的列表
HDJDJJDJ
JSJSJSJJSJS
SJJSHS::JS
Can you understand me Thanks for your help你能理解我吗 谢谢你的帮助
Maybe you can try something like this.也许你可以尝试这样的事情。
In Android Studio [File]->[Project Structure]->[Dependencies]->[Add Dependency]->[Library Dependency]-> choose 'app'(If you have multiple modules) -> search for 'GSON' -> choose implementation.在Android Studio中[文件]->[项目结构]->[依赖项]->[添加依赖项]->[库依赖项]->选择'app'(如果你有多个模块)->搜索'GSON'- > 选择实施。
Initialize Gson in java class:在 java class 中初始化 Gson:
Private Gson gson = new Gson();
String to List:要列出的字符串:
List<T> myList = new ArrayList<T>();
String myString = gson.toJson(myList);
List to string:列表到字符串:
Type myType = new TypeToken<List<T>>(){}.getType();
myList = gson.fromJson(myString, myType);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.