How do I convert a JSON array into a Java List. I'm using svenson

我与影子孤独终老i 提交于 2020-01-11 05:40:09

问题


I am trying to convert multiple objects of the same type into a List in Java. For example, my json would be:

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

I have a class:

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;
    }
...
}

I want to be able to turn the json string I get into a list of Example objects. I would like to do something like this:

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

Doing this I get an error:

Cannot set property Example on class java.util.ArrayList

回答1:


You cannot convert this json to List but you can convert this to Map.
See your json String:

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

Here "Example" is key(String) and value is List object of Example.

Try this:

 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());
     }
 }

Full code of 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;
    }
}

OutPut:

VALUE :->a1
VALUE :->a2
VALUE :->a3



回答2:


I solved it by modifying my JSON to be in the form:

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

Then I used the java code:

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);
    }



回答3:


i have a jsonstring like this :

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

and convert it to list by this snippet of code:

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")));
    }
}

i use net.sf.json-lib jar file.




回答4:


     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);


来源:https://stackoverflow.com/questions/10722587/how-do-i-convert-a-json-array-into-a-java-list-im-using-svenson

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!