banner
指数爆炸

指数爆炸

我做了对饭 !
github
bilibili

Before converting the string to JSON, take an extra step.

Problem#

At first glance, the following code seems seamless:

// Define format
final MediaType MEDIA_TYPE_MARKDOWN = MediaType.parse("application/json; charset=UTF-8");
// Create object
final OkHttpClient client = new OkHttpClient();

// The answer here can be any string
String reqData = "{\n" +
        "  \"req_data\": {\n" +
        "    \"text\": \"" +
        answer +
        "\\n\",\n" +
        "    \"image_ids\": [],\n" +
        "    \"mentioned_user_ids\": []\n" +
        "  }\n" +
        "}";

// Pass reqData as the request body
Request request = new Request.Builder()
        .url("https://api.zsxq.com/v2/topics/" + t.getTopicId() + "/comments")
        .post(RequestBody.create(MEDIA_TYPE_MARKDOWN, reqData))
        .addHeader("cookie", cookie)
        .addHeader("Content-type", "application/json; charset=UTF-8")
        .build();

But if there are line breaks in the answer:

answer = "Jiaxing University is a comprehensive university.\n\nJiaxing University offers undergraduate programs...";

Then the resulting reqData will have a problem:

{
  "req_data": {
    "text": "Jiaxing University is a comprehensive university.

Jiaxing University offers undergraduate programs...\n",
    "image_ids": [],
    "mentioned_user_ids": []
  }
}

Obviously, the format of this json is problematic

Solution#

We expect the reqData to be like this:

{
  "req_data": {
    "text": "Jiaxing University is a comprehensive university.\n\nJiaxing University offers undergraduate programs...\n",
    "image_ids": [],
    "mentioned_user_ids": []
  }
}

So we need to modify the answer:

answer = answer.replace("\n", "\\n");

String reqData = "{\n" +
        "  \"req_data\": {\n" +
        "    \"text\": \"" +
        answer +
        "\\n\",\n" +
        "    \"image_ids\": [],\n" +
        "    \"mentioned_user_ids\": []\n" +
        "  }\n" +
        "}";
Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.