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

5

我将尝试在Java中将多个相同类型的对象转换为List。例如,我的json如下:

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

我有一个类:

public class Example {
    private String foo;
    private String bar;
    private String fubar;
    public Example(){};
    public void setFoo(String f){
        foo = f;
    }
    public void setBar(String b){
        bar = b;
    }
    public void setFubar(String f){
        fubar = f;
    }
...
}

我希望能将收到的json字符串转换成一个Example对象列表。我想要做的事情如下:

JSONParser parser = new JSONParser();
parser.addTypeHint(".Example[]", Example.class);
List<Example> result = parser.parse(List.class, json);

这样做会出现错误:
Cannot set property Example on class java.util.ArrayList

1
@Ted Hopp:感谢您创建/添加svenson标签。 - Boundless
4个回答

4

您无法将此 json 转换为 List,但可以将其转换为 Map
请查看您的 json String

...
"Example": [
        {
            "foo": "a1",
            "bar": "b1",
            "fubar": "c1"
        },
        {
            "foo": "a2",
            "bar": "b2",
            "fubar": "c2"
        },
        ...
]
}
"Example"是关键字(字符串),而值是Example的List对象。

尝试这样做:

 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

谢谢您的回复。这个不起作用。当它到达以下行时:for (Example example : entry.getValue()) { 我收到以下错误:java.util.HashMap无法转换为com.xxx.Example。 - Boundless
@Boundless - 不可能的。我会更新完整的代码示例。我只是回复了你为什么以及在哪里出错了。谢谢。 - Subhrajyoti Majumder
谢谢,这个完美地解决了问题。我之前不确定问题出在哪里,但现在它能够按需工作了。 - Boundless

4
我通过修改JSON格式来解决了这个问题,修改后的格式如下:
[
    {
        "foo": "a1",
        "bar": "b1",
        "fubar": "c1"
    },
    {
        "foo": "a2",
        "bar": "b2",
        "fubar": "c2"
    },
    {
        "foo": "a3",
        "bar": "b3",
        "fubar": "c3"
    }
]

那我使用了Java代码:

JSONParser parser = new JSONParser();
    ArrayList list = parser.parse(ArrayList.class, json);
    List<Example> result = new ArrayList<Example>();
    for(int i = 0 ; i < list.size() ; i++){
        HashMap<String, String> map = (HashMap) list.get(i);
        Example example = new Example();
        example.setFoo(map.get("foo"));
        example.setBar(map.get("bar"));
        example.setFubar(map.get("fubar"));
        result.add(example);
    }

1
我有一个像这样的JSON字符串:

[
{"author":"amahta","bookId":1,"bookName":"name"},
{"author":"amahta2","bookId":2,"bookName":"name2"}
]

使用以下代码片段将其转换为列表:

List<BookVO> listdata = new ArrayList<BookVO>();

JSONArray jArray = JSONArray.fromObject(booklist);
if (jArray != null) {
    for (int i = 0; i < jArray.size(); i++) {
        JSONObject obj = JSONObject.fromObject(jArray.get(i));
        listdata.add(new BookVO(Long.valueOf(obj.get("bookId")), obj.get("bookName"), obj.get("author")));
    }
}

我使用net.sf.json-lib的jar文件。

0
     String paymentMethod = "[{\"paymentType\":\"google_iap\",\"msisdn\":1486890084928,\"operator\":\"maroc_ma\",\"paymentMethod\":\"maroc_ma\",\"reactivationEnabled\":true }]";

     PaymentMethod mop = null;
        try {
            mop = mapper.readValue(paymentMethod, PaymentMethod.class);
        } catch (Exception e) {
            logger.warn("Error while parsing paymentMethod = " + paymentMethod + " \n" + e);
        }

     List<PaymentMethod> result = new ArrayList<PaymentMethod>();
     result.add(mop);

     billingInfo.setPaymentMethods(result);

1
如果你不仅仅是堆积一堵代码墙,而是添加注释或描述解决方案的方式,那么这个会更有用。 - Whit Waldo

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接