gpt4 book ai didi

java - 如何将 Multiple 数组转换为 Json 数组并将 Json 添加到 hashmap

转载 作者:行者123 更新时间:2023-12-02 10:55:59 24 4
gpt4 key购买 nike

我想将这个 Json 字符串转换为数组。我的 HashMap 名为“HASHMRM”这是我的 Json 字符串:

[
{"id":1,"name":"hamid"},
{"id":2,"name":"mohamad"},
{"id":3,"name":"ali"},
{"id":4,"name":"john"},
{"id":5,"name":"smith"}
]

我想将这个 Json 字符串转换为这样的数组

String myJsonstring ="[{"id":1,"name":"hamid"},{"id":2,"name":"mohamad"},{"id":3,"name":"ali"},{"id":4,"name":"john"},{"id":5,"name":"smith"}]";
string[] AA = Jsons.....

int i =0;
while(i<string.lenght)
{
HASHMRM.put(AA[i].split()//First, AA[i].split()//second);
i++;
}

最佳答案

使用Gson .

首先,您需要与您的数据匹配的 POJO 类。

class MyUser {
int id;
String name;
}


然后,将字符串转换为 POJO 类的列表。

// This is your string.
String myJsonString = "[{\"id\":1,\"name\":\"hamid\"},{\"id\":2,\"name\":\"mohamad\"},{\"id\":3,\"name\":\"ali\"},{\"id\":4,\"name\":\"john\"},{\"id\":5,\"name\":\"smith\"}]";

// Create new Gson object.
Gson gson = new Gson();

// Convert
List<MyUser> userList = gson.fromJson(myJsonString, new TypeToken<List<MyUser>>() {
}.getType());


接下来,使用它!

for (MyUser u : userList) {
HASHMRM.put(u.id, u.name);
}

请记住:我建议您不要使用 HASHMRM 作为变量名称,而是使用 Java 常规驼峰命名法 HashMRM

关于java - 如何将 Multiple 数组转换为 Json 数组并将 Json 添加到 hashmap,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51741693/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com