1

I have a problem deserializing a javascript array to c# List class, have read other answers on SO but did not solve my issue.

The Array of Objects

"{\"Id\":\"87\",\"Name\":\"Product x\",\"Cost\":200000,\"Tag\":\"Product_x\"},
 {\"Id\":\"88\",\"Name\":\"Product y\",\"Cost\":100000,\"Tag\":\"Product_y\"}"

The products are posted as FormData, so i receive them in the format above.

Product Model

public class Product {
    public int Id {get; set;}
    public String Name {get; set;}
    public decimal Cost {get; set;}
    public string Tag {get; set;}
 }

And i have a ViewModel

public class ProductViewModel {
    [JsonProperty("SerializedProducts")]
        public string SerializedProducts{ get; set; } // So this model returns the array of objects above

    // Deserializes the SerializedProduct and converts to List of Products.
        public List<Product> Products
        {
            get { return JsonConvert.DeserializeObject<List<Product>>(SerializedProducts); } 
            set { }
        }
 }

Error Message Cannot deserialize the current JSON object (e.g. {\"name\":\"value\"}) into type 'System.Collections.Generic.List `1[Product]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.

What i observed I expect SerializedProducts to return an array of object like this

"[{\"Id\":\"87\",\"Name\":\"Product x\",\"Cost\":200000,\"Tag\":\"Product_x\"},
 {\"Id\":\"88\",\"Name\":\"Product y\",\"Cost\":100000,\"Tag\":\"Product_y\"}]"

Please i need help. Thank you!

Update

Javascript post

function extractAndFormatFormData(formId) {
    var formData = new FormData();
    var products = [];
    var product = new Product(Id, Name, Cost, Tag);

    // Add product to array
    products.push(JSON.stringify(product));

    // Add products to form
    formData.append('SerializedProducts', products);

    // I'm also attaching a txt file. This is not an issue at the moment
    formData.append('UploadedForm', uploadedFile);

    return formData;
}

Ajax post

var formatedFormData = extractAndFormatFormData(formId);
        var url = '/Dashboard/provision/';
        $.ajax({
            url: url,
            data: formatedFormData,
            type: 'POST',
            datatype: 'json',
            contentType: false,
            processData: false,
            cache: false,
            success: function (data) {
                $('#planDetails').append(data);
            },
            error: function (err) {
                console.log(err);
            }
        });
5
  • 2
    The "array of objects" isn't one, the JSON is invalid. To be an array, it would be within[...] (which you have in the example at the end). So if you're really receiving it without, add the square brackets. Commented Apr 29, 2017 at 15:58
  • Thank you @T.J. Crowder , this was what i suspected too. How can i fix it. i have updated my question to include the Form Posted. Can you help? Commented Apr 29, 2017 at 16:16
  • Looks like Cleiton's already sorted it out. :-) Commented Apr 29, 2017 at 16:47
  • O yes, great sir. Thank you too for pointing out the actual problem. Commented Apr 29, 2017 at 16:56
  • Suggest you also refer this answer. Stringifying your data and sensdng it as FormData and then deserializing it again in a model property is unnecessary.. Commented Apr 29, 2017 at 23:27

1 Answer 1

4

In Javascript, use stringfy on products array and not in item of array.

Code:

function extractAndFormatFormData(formId) {
    var formData = new FormData();
    var products = [];
    var product = new Product(Id, Name, Cost, Tag);

    // Add product to array
    products.push(product);

    // Add products to form
    formData.append('SerializedProducts', JSON.stringify(products));

    // I'm also attaching a txt file. This is not an issue at the moment
    formData.append('UploadedForm', uploadedFile);

    return formData;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.