gpt4 book ai didi

java - 如何在restful中将map转换为json

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

在我的项目中,我动态生成 json 并将其放入 Map<String,Student>() 中注意: key 是动态的所以我的回复打印如下:

"entry": [
{
"key": "student1",
"value": {
"name":selva
}
},
{
"key": "student2",
"value": {
"name":"kumar"
}
}
]

但我预期的回应是:

[
"student1" : {
"name":"kumar"
},
"student2" : {
"name":"selva"
}
]

**My keys are dynamic here...**

如何在 Jersey 上达到预期的效果。pom.xml

<!-- Json dependency -->
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-moxy</artifactId>
</dependency>

任何帮助将不胜感激!!!!

最佳答案

/**
* JSONObjects can be built from a Map<String, Object>.
* In this test all of the map entries are valid JSON types.
*/
@Test
public void jsonObjectByMap() {
Map<String, Object> map = new HashMap<String, Object>();
map.put("trueKey", new Boolean(true));
map.put("falseKey", new Boolean(false));
map.put("stringKey", "hello world!");
map.put("escapeStringKey", "h\be\tllo w\u1234orld!");
map.put("intKey", new Long(42));
map.put("doubleKey", new Double(-23.45e67));
JSONObject jsonObject = new JSONObject(map);

// validate JSON
Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString());
assertTrue("expected 6 top level items", ((Map<?,?>)(JsonPath.read(doc, "$"))).size() == 6);
assertTrue("expected \"trueKey\":true", Boolean.TRUE.equals(jsonObject.query("/trueKey")));
assertTrue("expected \"falseKey\":false", Boolean.FALSE.equals(jsonObject.query("/falseKey")));
assertTrue("expected \"stringKey\":\"hello world!\"", "hello world!".equals(jsonObject.query("/stringKey")));
assertTrue("expected \"escapeStringKey\":\"h\be\tllo w\u1234orld!\"", "h\be\tllo w\u1234orld!".equals(jsonObject.query("/escapeStringKey")));
assertTrue("expected \"doubleKey\":-23.45e67", Double.valueOf("-23.45e67").equals(jsonObject.query("/doubleKey")));
}

关于java - 如何在restful中将map转换为json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37855500/

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