gpt4 book ai didi

java - 如何从 JSONObject 字符串中删除引号前的反斜杠?

转载 作者:行者123 更新时间:2023-11-30 06:40:39 26 4
gpt4 key购买 nike

背景

我有一个由类动态创建的字符串(记录)列表。每条记录可能有不同的键(例如,第一个是 favorite_pizza,第二个是 favorite_candy)。

// Note: These records are dynamically created and not stored
// in this way. This is simply for display purposes.
List<String> records =
Arrays.asList(
"{\"name\":\"Bob\",\"age\":40,\"favorite_pizza\":\"Cheese\"}",
"{\"name\":\"Jill\",\"age\":22,\"favorite_candy\":\"Swedish Fish\"}");

然后将记录列表传递给单独的 HTTP 请求类。

public Response addRecords(List<String> records) {
...
}

在 HTTP 请求服务中,我想构建一个 JSON 请求主体:

{
"records": [
{
"name": "Bob",
"age": 40,
"favorite_pizza": "Cheese"
},
{
"name": "Jill",
"age": 22,
"favorite_candy": "Swedish Fish"
}
]
}

我正在使用 org.json.JSONObject添加 records 键并创建请求正文:

JSONObject body = new JSONObject();

// Add the "records" key
body.put("records", records);

// Create the request body
body.toString();

问题

当我在 IntelliJ 中运行我的 junit 测试时,请求主体在每个引号前包含一个反斜杠:

org.junit.ComparisonFailure: 
Expected :"{"records":["{"name":"Bob","age":40,"favorite_pizza":"Cheese"}","{"name":"Jill","age":22,"favorite_candy":"Swedish Fish"}"]}"
Actual :"{"records":["{\"name\":\"Bob\",\"age\":40,\"favorite_pizza\":\"Cheese\"}","{\"name\":\"Jill\",\"age\":22,\"favorite_candy\":\"Swedish Fish\"}"]}"

当我发出请求时,它失败了,因为正文格式不正确:

{
"records": [
"{\"name\":\"Bob\",\"age\":40,\"favorite_pizza\":\"Cheese\"}",
"{\"name\":\"Jill\",\"age\":22,\"favorite_candy\":\"Swedish Fish\"}"
]
}

问题

  • 为什么 JSONObject 在每个引号前都包含反斜杠?
  • 如何删除反斜杠?

最佳答案

您正在创建一个字符串列表,这不是您想要的。

您应该创建一个对象列表( map )

Map<String, Object> m1 = new LinkedHashMap<>();
m1.put("name", "Bob");
m1.put("age", 40);
m1.put("favorite_pizza", "Cheese");

LinkedHashMap<String, Object> m2 = new LinkedHashMap<>();
m2.put("name", "Jill");
m2.put("age", 22);
m2.put("favorite_candy", "Swedish Fish");
List<LinkedHashMap<String, Object>> records = Arrays.asList(m1,m2);

JSONObject body = new JSONObject();

// Add the "records" key
body.put("records", records);

这是一个很常见的错误(看起来),尝试序列化格式类似于 json 对象的字符串与传递对象本身是一回事。

更新:

或者如果你有一个 json 序列化的对象列表,那么......

List<String> recordSource =
Arrays.asList(
"{\"name\":\"Bob\",\"age\":40,\"favorite_pizza\":\"Cheese\"}",
"{\"name\":\"Jill\",\"age\":22,\"favorite_candy\":\"Swedish Fish\"}");
List<JSONObject> records =
recordSource.stream().map(JSONObject::new).collect(Collectors.toList());

JSONObject body = new JSONObject();

// Add the "records" key
body.put("records", records);
System.out.println(body.toString());

关于java - 如何从 JSONObject 字符串中删除引号前的反斜杠?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57628802/

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