Java - JSON 输出并不像控制台建议的那样

Java - JSON output is not expected as what console suggests

我是 Java 和编写 API 的新手。

我基本上有两个东西:一个名为 db 的 HashMap 应该作为 JSON 返回,一个名为 defaultParameters 的 ArrayList。基本上应用程序的作用如下:

db 基本上包含一个键值对对象数组,当用户向该地址发出 GET 请求时,应将其作为 JSON 返回。

defaultParameters 基本上是默认键值对的列表。如果该对象中没有键值对,则该对象采用该默认键值对。

我能够让它显示在控制台上,但由于某种原因,当我执行获取请求时,更新的值没有出现在 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();
    }

项目的片段class

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 请求会产生以下结果:

在控制台上(Something:notsomething)是新的:

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 反映控制台正在做什么。有人有什么想法吗?

好吧,经过一番思考,我想出了办法。

我更改了我的代码

public class Item {

public class Item extends HashMap<String, String> {

并移除

private HashMap<String, String> item = new HashMap<>();

这意味着我必须将 item 更改为 this。我想因为我将把每个实例用作散列图,所以我也可以扩展也会更改项目实例的散列图。

感谢大家的帮助。该评论使我对我正在尝试做的事情有了更深入的了解,从而找到了解决方案。