您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

如何将JSON数组转换为Java列表。我正在使用svenson

如何将JSON数组转换为Java列表。我正在使用svenson

您不能将此json转换为,List但可以将其转换为Map。 看到你的json String

...
"Example": [
        {
            "foo": "a1",
            "bar": "b1",
            "fubar": "c1"
        },
        {
            "foo": "a2",
            "bar": "b2",
            "fubar": "c2"
        },
        ...
]
}

试试这个:

 parser.addTypeHint("Example[]", Example.class);
 Map<String,List<Example>> result1 = parser.parse(Map.class, json);
 for (Entry<String, List<Example>> entry : result1.entrySet()) {
     for (Example example : entry.getValue()) {
          System.out.println("VALUE :->"+ example.getFoo());
     }
 }

的完整代码Example

import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.svenson.JSONParser;

public class Test {
    public static void main(String[] args) {
        JSONParser parser = new JSONParser();
        parser.addTypeHint(".Example[]", Example.class);
        String json = "{" + "\"Example\": [" + "{" + "\"foo\": \"a1\","
                + "\"bar\": \"b1\"," + "\"fubar\": \"c1\"" + "}," + "{"
                + "\"foo\": \"a2\"," + "\"bar\": \"b2\"," + "\"fubar\": \"c2\""
                + "}," + "{" + "\"foo\": \"a3\"," + "\"bar\": \"b3\","
                + "\"fubar\": \"c3\"" + "}" + "]" + "}\"";
        parser.addTypeHint("Example[]", Example.class);
        Map<String, List<Example>> result1 = parser.parse(Map.class, json);
        for (Entry<String, List<Example>> entry : result1.entrySet()) {
            for (Example example : entry.getValue()) {
                System.out.println("VALUE :->" + example.getFoo());
            }
        }
    }
}

public class Example {
    private String foo;
    private String bar;
    private String fubar;
    public Example(){}
    public void setFoo(String foo) {
        this.foo = foo;
    }
    public String getFoo() {
        return foo;
    }
    public void setBar(String bar) {
        this.bar = bar;
    }
    public String getBar() {
        return bar;
    }
    public void setFubar(String fubar) {
        this.fubar = fubar;
    }
    public String getFubar() {
        return fubar;
    }
}

VALUE :->a1
VALUE :->a2
VALUE :->a3
java 2022/1/1 18:41:33 有577人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶