繁体   English   中英

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

[英]How do I remove backslashes before quotes from a JSONObject string?

背景

我有一个由类动态创建的字符串(记录)列表。 每个记录可以具有不同的密钥(例如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<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());

如果您的记录字符串已经是有效的 json,您可以

  1. 迭代它们,一次将它们转换为JSONObject (参见此处),然后将结果添加到JSONArray ,您可以根据需要对其进行操作。

  2. 完全手动创建数组,因为它只是方括号内的逗号分隔记录字符串。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM