gpt4 book ai didi

java - 在java中从字符串中读取json

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:15:54 26 4
gpt4 key购买 nike

如果JSON数据在字符串中,如何从下面的JSON中读取数据

{
"name": "test",
"values": [
{
"valu": "23",
"valu1": "24",
"valu2": "25"
}
]
}

最佳答案

使用 GsonGson#fromJson 方法之一

fromJson(String, Class)

YourType o = new Gson().fromJson("your json string", YourType.class);

fromJson(Reader, Class)

YourType o = new Gson().fromJson(new StringReader("your json string"), 
YourType.class);

简单的例子:

定义要将 json 数据映射到的类:

static class Hobby {
Hobby(String n) { name = n; }
String name;
@Override
public String toString() {
return "Hobby [name=" + name + "]";
}
}

static class Person {
String firstName, lastName;
int age;
List<Hobby> hobbies = new ArrayList<Hobby>();
@Override
public String toString() {
return "Person [firstName=" + firstName + ", lastName=" + lastName
+ ", age=" + age + ", hobbies=" + hobbies + "]";
}
}

现在使用以下 Json 字符串进行测试

@Test
public void fromJson() {
Person o = new Gson().fromJson(
"{\r\n" +
" \"firstName\":\"John\",\r\n" +
" \"lastName\":\"Doe\",\r\n" +
" \"age\":24,\r\n" +
" \"hobbies\":[\r\n" +
" {\r\n" +
" \"name\":\"Programming\"\r\n" +
" },\r\n" +
" {\r\n" +
" \"name\":\"Sports\"\r\n" +
" }\r\n" +
" ]\r\n" +
"}",
Person.class);
System.out.println(o.toString());
}

这打印:

Person [firstName=John, lastName=Doe, age=24, hobbies=[Hobby [name=Programming], Hobby [name=Sports]]]

查看类的javadoc Gson对于其他选择。也看看他们的 user-guide

关于java - 在java中从字符串中读取json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20632151/

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