如何将generic或rawtypes List转换为String数组

时间:2015-01-14 21:51:24

标签: java arrays json list raw-types

我正在创建一个泛型或rawtypes数据列表,并试图将它存储在一个String数组中,但它失败了 -

线程“main”中的异常java.lang.ArrayStoreException

这里是代码片段,这里是函数我试图将rawtypes转换为字符串数组但是面对上面给出的数组,如果你可以采取下面给出的例子并指导我在这里做错了什么 -

 public class Parsing {


        public static void main(String[] args) throws JsonParseException, JsonMappingException, IOException {

            //List<JsonGen> jsongenShow = null;
            String url1 = "http://www.xxxxxxxx.com/radish/v20/dol/home/carousels/shows.json";
            List[] nwDetails = getShowNWdetailsParser(jsongenShow, url1);

        }


        @SuppressWarnings("rawtypes")
        public static List[] getShowNWdetailsParser (List<JsonGen> jsongenShow, String url ) throws JsonParseException, JsonMappingException, IOException
        {
            URL jsonUrl = new URL(url);
            ObjectMapper objmapper = new ObjectMapper();
            jsongenShow = objmapper.readValue(jsonUrl, new TypeReference<List<JsonGen>>() {});
            List [] shows = new List [jsongenShow.size()]; 

             String[] showsArr = new String[jsongenShow.size()];
             showsArr= (String[])jsongenShow.toArray(showsArr);

            for (int i=0; i == jsongenShow.size(); i++ ){

                System.out.println(showsArr[i]);
            }
int i = 0;
        for(JsonGen element : jsongenShow) {
            shows[i]=element.getNetworks();

            i++;
            }
        for(int j =0; j<shows.length;j++)
        {
            System.out.println(showsArr[j]);

        }


            return shows;   
        }

    }

2 个答案:

答案 0 :(得分:0)

Java无法自动将对象转换为String。您必须遍历源列表并填充目标数组,并自己将JsonGen映射到String。

非常不幸的是,API允许您的代码在所有

编译

答案 1 :(得分:0)

经过一些实验,我终于找到了做到这一点的方法。

 @SuppressWarnings("rawtypes")
    public static String[] getShowNWdetailsParser (List<JsonGen> jsongenShow, String url ) throws JsonParseException, JsonMappingException, IOException
    {
        URL jsonUrl = new URL(url);
        ObjectMapper objmapper = new ObjectMapper();
        List<JsonGen> jsongenShow_1 = objmapper.readValue(jsonUrl, new TypeReference<List<JsonGen>>() {});
        List [] shows = new List [jsongenShow_1.size()]; 
        String[] showsArr = new String[jsongenShow_1.size()];
        for(JsonGen element : jsongenShow_1) {
            shows[i]=element.getNetworks();
            showsArr[i]=shows[i].toString();
            i++;
            }
        for(int j =0; j<shows.length;j++)
        {
            System.out.println(showsArr[j]);

        }

        return showsArr;    
    }