Question

Here is my Json:

{"Username":"Test","ProductIds":"[30, 50]","RouteName":"ABCD"}

And here is my object:

public class SuggestMobileModel
    {
        public string Username { get; set; }
        public List<int> ProductIds { get; set; }
        public string RouteName { get; set; }
    }

When I convert that Json to that object, I can receive the Username, RouteName, but the ProductIds is always null. It only works when I remove the quotation in ProductIds value, like this:

{"Username":"Test","ProductIds":[30, 50],"RouteName":"ABCD"}

What can I do now to deserialize successfully without removing the code? That Json is generated by code, so it always has that quotes.

---EDIT!!!---

Here is the Java code created that Json string. Does it has any error? It's using org.json library.

// 1. create HttpClient
            HttpClient client = new DefaultHttpClient();
            HttpResponse response;

            // 2. make POST request to the given URL
            HttpPost httpPost = new HttpPost(urlSuggestRoute);

            String json = "";

            // 3. build jsonObject
            JSONObject jsonObject = new JSONObject();
            jsonObject.accumulate("Username", User.getUsername());
            List<Integer> listProductIds = new ArrayList<Integer>();
            if (Cart.getCart() != null && Cart.getSize() > 0) {
                for (int i = 0; i < Cart.getSize(); i++) {
                    listProductIds.add(Cart.getCartItem(i)
                            .getProductAttribute().getProductId());
                }
            }
            jsonObject.accumulate("ProductIds", listProductIds);
            jsonObject.accumulate("RouteName", txtRoute.getSelectedItem()
                    .toString());

            // 4. convert JSONObject to JSON to String
            json = jsonObject.toString();

            // 5. set json to StringEntity
            StringEntity se = new StringEntity(json);

            // 6. set httpPost Entity
            httpPost.setEntity(se);

            // 7. Set some headers to inform server about the type of the
            // content
            httpPost.setHeader("Accept", "application/json");
            httpPost.setHeader("Content-type", "application/json");

            // 8. Execute POST request to the given URL
            HttpResponse httpResponse = client.execute(httpPost);
Was it helpful?

Solution 2

OK, I've figured it out. In the code which produces the Json, I should have used JsonArray instead of List<Integer>, then the library won't put the quotation mark around the array.

Thanks a lot for your help :)

OTHER TIPS

It is not valid JSON to put double quotes around array values (see language grammar at http://json.org/). Therefore your JSON parser will probably not support that.

Additional background information: your JSON defines ProductIds as a pair with the string value [30, 50].

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top