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

时间:2019-08-23 15:02:09

标签: java json

背景

我有一个由类动态创建的字符串(记录)列表。每条记录可以具有不同的键(例如,第一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在每个引号前都包含反斜杠?
  • 如何删除反斜杠?

2 个答案:

答案 0 :(得分:4)

您要创建的字符串列表不是您想要的。

您应该改为创建对象列表(地图)

    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());

答案 1 :(得分:0)

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

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

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

相关问题