我要发送到前端的服务器端自定义对象中有一个Java TreeMap frutitas
。
我使用javax.ws
和jackson
进行序列化。我在前端获得的数据如下:
{ "frutitas": {
"entry": [
{
"key": "fruto 1",
"value": "el banano"
},
{
"key": "fruto 2",
"value": "el pineapple"
}
]
}
但是我想要得到这样的东西,这实际上是我在要上传到后端的对象中发送“ frutitas”映射的方式:
{
"frutitas": {
"fruto 1": "el banano",
"fruto 2": "el pineapple"
}
}
答案 0 :(得分:0)
您可以按预期将TreeMap转换为JSONObject。这是示例,以便您了解。
JSONObject jsonObject = new JSONObject(yourTreeMap);
如果打印jsonObject,输出将是这样。
{"fruto 1":"el banan","fruto 2":"el pineapple"}
JSONObject main = new JSONObject();
main.put("frutitas", jsonObject);
{
"frutitas": {
"fruto 1": "el banano",
"fruto 2": "el pineapple"
}
}
答案 1 :(得分:0)
库Json-Jackson(也称为FasterXML)是JSON序列化-反序列化的事实上的标准。它工作迅速并且被广泛使用。下面是我编写的用于序列化/反序列化任何对象的简单类。但是总的来说,您需要查看ObjectMapper类以了解其工作原理。这是项目的Github link。您可以使用以下Maven依赖项:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.9</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
<version>2.9.9</version>
</dependency>
我的课堂示例
package com.bla.json.utils;
import java.io.IOException;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectReader;
import com.fasterxml.jackson.databind.ObjectWriter;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
public class JsonUtil {
private static final ObjectReader objectReader;
private static final ObjectWriter objectWriter;
static {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.registerModules(new JavaTimeModule());
objectMapper.enableDefaultTyping();
objectReader = objectMapper.reader();
objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
objectWriter = objectMapper.writer();
}
public static String writeObjectToJsonString(Object object) throws JsonProcessingException {
String jsonData = null;
if (object != null) {
jsonData = objectWriter.writeValueAsString(object);
}
return jsonData;
}
public static <T> T readObjectFromJsonString(String s, Class<T> type) throws IOException {
T data = objectReader.forType(type).readValue(s);
return data;
}
}
答案 2 :(得分:0)
另一种选择是使用gson。
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.5</version>
</dependency>
还有包含地图的类:
public class FrutitasClass {
private Map<String, String> frutitas;
}
下面的代码将进行转换:
Gson gson = new GsonBuilder().setPrettyPrinting().create();
String json = gson.toJson(frutitasClassObject);
出局:
{
"frutitas": {
"fruto 1": "el banano",
"fruto 2": "el pineapple"
}
}