gpt4 book ai didi

java - Arraylist 到字符串并返回到 arraylist

转载 作者:行者123 更新时间:2023-12-02 11:40:23 24 4
gpt4 key购买 nike

我想将 (TestObject) 的 ArrayList 转换为字符串,反之亦然。我还附上了主要 Activity ,以便您可以看到我想要创建的方法。

MainActivity:ArrayList 的创建位置,需要转换为 String。

public class MainActivity extends AppCompatActivity {
ArrayList<TestObject> testObjects;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

testObjects = new ArrayList<>();
testObjects.add(new TestObject("Name1", "Attribute1"));
testObjects.add(new TestObject("Example", "Example"));
}


private String convertObjectArrayToString(ArrayList<TestObject> arrayToBeConverted){
return null;
}

private ArrayList<TestObject> convertStringToObjectArray(){

return null;
}

}

ArrayList 中的对象:

public class TestObject {

private String name;
private String attribute;

TestObject(String name, String attribute){
this.name = name;
this.attribute = attribute;
}

public void setAttribute(String attribute) {
this.attribute = attribute;
}

public void setName(String name) {
this.name = name;
}

public String getName() {
return name;
}

public String getAttribute() {
return attribute;
}
}

最佳答案

//ArrayList 到字符串转换:

String listToJson = new Gson().toJson(testObjects);

//ViceVersa字符串获取数组列表:

Type listType = new TypeToken<List>() {}.getType();

List myModelList = new Gson().fromJson(listToJson, listType);

更新:

 myModelList = gson.fromJson(br, new TypeToken<ArrayList< TestObject >>(){}.getType());

关于java - Arraylist 到字符串并返回到 arraylist,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48617495/

24 4 0