C# – JSON error : expecting state ‘element’.. encountered ‘text’ with name ”, namespace ”

cjqueryjson

I am trying to send Json data from Ajax request to a restful web service.
It's not the first time I do it but this time the type is a more complex one.

This is the web service method :

InstanceServiceResponse<BlogPostData> CreatePost(ObjectCollection ressources);

The object ObjectCollection is defined as follow :

public class ObjectCollection : ISerializable, IEnumerable
    {
        Dictionary<string, object> objectsValue;

        public ObjectCollection()
        {
            objectsValue = new Dictionary<string, object>();
        }

        public ObjectCollection(IDictionary<string, object> parameters)
        {
            objectsValue = new Dictionary<string, object>(parameters);
        }

        ...
        ...
   }

The ressources parameter is created like this :

function GetRessources() {
    var Ressources = [];
    $.each($("#ressources-holder > div"), function (key, value) {
        Ressources.push( { "name": $(value).children().first().text().slice(0, -1), "id": $(value).attr('id') } );
    });
    return Ressources;
}

And the Json created is :

[{"name":"tototititata","id":"107875"},{"name":"test","id":"107877"}]

Regarding the error and what i have seen in other SO posts related to the same question it seems it's because of the name of the parameters.

But, and this is why I am posting a new question, my type (ObjectCollection) doesn't have any public fields on witch I can "bind" my parameters.

And am a bit in the dark right now and any help and advice will be very much appreciated.

EDIT

Since I didn't found any applicable solution I have use a bypass.
I am sending a Dictionary<string, object> like so :

function GetRessources() {
    var Ressources = [];
    $.each($("#ressources-holder > div"), function (key, value) {
        Ressources.push({ "Key": $(value).children().first().text().slice(0, -1), "Value": $(value).attr('id') });
    });
    return Ressources;
}

And then server side just creating a new ObjectCollection with it.

This isn't going to help anyone I think but I'll keep the question alive for posterity.

Best Answer

In order to send a json object correctly, the object must relate to the fields it is bound to.

Meaning, if you want to send name in you json request, you have to define a 'name' field and send it in the json request, else, you will not be able to pass it successfully.

What you need to do here, is either try and create related fields in order to worker properly with the json, create an entity or even try to work something in the json collection entity.

Or, instead of using json push, try to use json ajax request and see how that works.

Anyhow, fastest solution for you here, as far as I can see it, is to work with public fields as much as you can.