Pawan
Pawan

Reputation: 32321

Parse Json and construct an array

I am parsing a JSON as shown below

[
    {
        "vendor_itms_arr": [
            "265",
            "141",
            "148"
        ]
    }
]

This is my program

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;


public class MrTest {

    public static void main(String args[]) throws JSONException
    {
        String json = "[\r\n" + 
                "    {\r\n" + 
                "        \"vendor_itms_arr\": [\r\n" + 
                "            \"265\",\r\n" + 
                "            \"141\",\r\n" + 
                "            \"148\"\r\n" + 
                "        ]\r\n" + 
                "    }\r\n" + 
                "]";

        JSONArray array = new JSONArray(json);
        ArrayList<Integer> vendor_itms_arr = new ArrayList<Integer>();
        for(int i=0;i<array.length();i++)
        {
             JSONObject jb1 = array.getJSONObject(i);
             JSONArray jr1 = jb1.getJSONArray("vendor_itms_arr");
            if (jr1 != null) { 
                   int len = jr1.length();
                   for (int k=0;i<len;i++){ 
                       int val = (Integer) jr1.get(k);
                       vendor_itms_arr.add(val);
                   } 
                } 
        }
        System.out.println(vendor_itms_arr);
    }
}

I am getting

Exception in thread "main" java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer
    at MrTest.main(MrTest.java:36)

Could you please let me know how can i construct a array

 int constructed_array[] = { 265 , 141 , 148};

Upvotes: 0

Views: 54

Answers (2)

Anarki
Anarki

Reputation: 393

Change your program from Integer to String and try this :

String constructed_array[] = { "265", "141", "148" };
List<Integer> myNewList = new ArrayList<Integer>(constructed_array.length);
for (String str : constructed_array) {
    myNewList.add(Integer.parseInt(str));
}

Now the object myNewList contains [265, 141, 148].

Edit

For the primitive array you can do this :

String constructed_array[] = { "265", "141", "148" };
int[] myPrimitiveArray = new int[constructed_array.length];
for (int i = 0; i < constructed_array.length; i++) {
    myPrimitiveArray[i] = Integer.parseInt(constructed_array[i]);
}

myPrimitiveArray is a primitive array that contain [265, 141, 148].

Upvotes: 1

user1907906
user1907906

Reputation:

Use Integer.parseInt(String s):

int val = Integer.parseInt(jr1.get(k));

Upvotes: 4

Related Questions