我是 Java 和 API 编写新手。
我基本上有两件事:一个名为 db
的 HashMap(应以 JSON 形式返回)和一个名为 defaultParameters
的 ArrayList。该应用程序的基本功能如下:
db
基本上包含一个键值对对象数组,当用户向此地址发出 GET 请求时,应将其作为 JSON 返回。
defaultParameters
基本上是默认键值对的列表。如果该对象内没有键值对,则该对象将采用该默认键值对。
我能够让它显示在控制台上,但由于某种原因,当我执行 get 请求时,更新的值没有出现在 JSON 中。
以下是相关代码片段:
private static ArrayList<Item> DB = new ArrayList<>();
private static HashMap<String, String> defaultValues = new HashMap<>();
private void updateAllItems(){
for(Item item : DB){
for(Map.Entry entry : defaultValues.entrySet()){
String currentField = (String) entry.getKey();
String currentValue = (String) entry.getValue();
item.addField(currentField, currentValue);
}
}
}
@GET
@Produces(MediaType.APPLICATION_JSON)
public Response getAllItems() {
updateAllItems();
for(Item item : DB){
// Test code that I added
item.printItem();
}
return Response.ok(DB).build();
}
Item 类的片段
public class Item {
private HashMap<String, String> item = new HashMap<>();
public void addField(String key, String value){
item.put(key, value);
}
public void printItem(){
for(Map.Entry entry : item.entrySet()){
String currentField = (String) entry.getKey();
String currentValue = (String) entry.getValue();
System.out.println(currentField + ": " + currentValue);
}
}
}
执行 POST
请求并执行 GET
请求会产生以下结果:
在控制台上(某事:不是某事)是新的:
seller: Mrs. Fields
price: 49.99
title: Cookies
category: 42
something: notsomething
但是 JSON 响应:
[{"category":"42","seller":"Mrs. Fields","price":"49.99","title":"Cookies"}]
JSON 缺少控制台具有的新键值对。我试图让 JSON 反射(reflect)控制台正在做什么。大家有什么想法吗?
最佳答案
好吧,经过一番思考,我知道该怎么做了。
我更改了代码
public class Item {
到
public class Item extends HashMap<String, String> {
并删除
private HashMap<String, String> item = new HashMap<>();
这意味着我必须将item
更改为this
。我想既然我将使用每个实例作为 HashMap ,我也可以扩展 HashMap 来更改项目的实例。
感谢大家的帮助。该评论让我对我正在尝试做的事情有了更多的了解,从而找到了解决方案。
关于Java - JSON 输出并不像控制台所建议的那样,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60999545/