gpt4 book ai didi

java - 如何在java + Spring Boot中生成带有转义字符 "\n"的JSON

转载 作者:行者123 更新时间:2023-12-01 18:47:39 25 4
gpt4 key购买 nike

我正在使用 Java 中的 GSON(当前)生成此 json

{
"scheduleAt": "2020-01-16T09:45:29.361Z",
"serviceType": "TRUCK",
"stops": [
{
"location": {
"lat": "109.063753",
"lng": "312.998866"
},
"addresses": {
"en_IN": {
"displayString": "Please bring the BAG",
"country": "TH"
}
}
}
]
}

我期待以下一个:(预期)

{\n \"scheduleAt\": \"2018-12-31T14:30:00.00Z\",\n \"serviceType\": \"MOTORCYCLE\",\n \"requesterContact\": { \"name\": \"Peter Pan\", \"phone\": \"232\" },\n \"stops\": [\n {\n \"location\": { \"lat\": \"-6.255431000000001\", \"lng\": \"106.60114290000001\" },\n \"addresses\": {\n \"en_ID\": {\n \"displayString\":\n \"Jl. Perum Dasana Indah No.SD 3/ 17-18, RT.3/RW.1, Bojong Nangka, Klp. Dua, Tangerang, Banten 15810, Indonesia\",\n \"country\": \"ID\"\n }\n }\n },\n {\n \"location\": { \"lat\": \"-6.404722800000001\", \"lng\": \"106.81902130000003\" },\n \"addresses\": {\n \"en_ID\": {\n \"displayString\": \"Jl. Kartini, Ruko No. 1E, Depok, Pancoran MAS, Kota Depok, Jawa Barat 16431, Indonesia\",\n \"country\": \"ID\"\n }\n }\n }\n ],\n \"deliveries\": [\n {\n \"toStop\": 1,\n \"toContact\": {\n \"name\": \"mm\",\n \"phone\": \"9999999\"\n }\n }\n ]\n}\n'

如果我们在 JavaScript 中使用 JSON.stringfy(),我们会得到上面的 json。 谁能告诉我如何在 JAVA 中实现这一点

最佳答案

您可以使用 jackson 对象映射器来实现此目的。

ObjectMapper mapper = new ObjectMapper();
value = mapper.writeValueAsString(obj);

引用:

https://www.programcreek.com/java-api-examples/?class=com.fasterxml.jackson.databind.ObjectMapper&method=writeValueAsString

https://www.baeldung.com/jackson-object-mapper-tutorial

关于java - 如何在java + Spring Boot中生成带有转义字符 "\n"的JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59797809/

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