سؤال

Any help will be appreciated here.

I'm trying to use StackService. Text and JSON in order to get a list of objects, that each object contains a list.

Here is the definition of the classes:

[DataContract]
public class GroupingList
{
    [DataMember(Name = "id")]
    public int Id
    {
        get; set;
    }
    [DataMember(Name = "name")]
    public string Name
    {
        get; set;
    }
    [DataMember(Name = "form_field")]
    public string FormField
    {
        get;
        set;
    }

    [DataMember(Name = "groups")]
    public List<GroupingOptions> Groups
    {
        get; set;
    }
}

[DataContract]
public class GroupingOptions
{
    [DataMember(Name = "bit")]
    public string Bit
    {
        get; set;
    }
    [DataMember(Name = "name")]
    public string Name
    {
        get; set;
    }
    [DataMember(Name = "display_order")]
    public string DisplayOrder
    {
        get; set;
    }
    [DataMember(Name = "subscribers")]
    public int Subscribers
    {
        get; set;
    }
}

I'm using the 'PostJsonToUrl()' method, and receiving the following string as a return result:

"\n[{\"id\":14101,\"name\":\"Accounting1\",\"form_field\":\"hidden\",\"display_order\":\"0\",\"groups\":[{\"bit\":\"1\",\"name\":\"Interest\",\"display_order\":\"1\",\"subscribers\":null},{\"bit\":\"2\",\"name\":\"Register\",\"display_order\":\"2\",\"subscribers\":null}]}]"

Now, when I'm trying to call the FromJson(List<GroupingList>) method, I'm getting the following exception:

Type definitions should start with a '{', expecting serialized type 'GroupingList', got string starting with: 
[{"id":14101,"name":"Accounting1","form_field":"h

Can anyone direct me please whether this issue is related to the definition of the 'GroupingList' and 'GroupingOptions' classes? The return result of 'PostJsonToUrl()' is a list (with one entry in this case) that contain another list (with two items), so I don't understand why calling FromJson(List) fails.

Many thanks

هل كانت مفيدة؟

المحلول

The problem is \n symbol at the begining of the string. You can remove it first, and then desirialize GroupingList.

string result = "\n[{\"id\":14101,\"name\":\"Accounting1\",\"form_field\":\"hidden\",\"display_order\":\"0\",\"groups\":[{\"bit\":\"1\",\"name\":\"Interest\",\"display_order\":\"1\",\"subscribers\":0},{\"bit\":\"2\",\"name\":\"Register\",\"display_order\":\"2\",\"subscribers\":0}]}]";
result = result.Trim();
List<GroupingList> list = result.FromJson<List<GroupingList>>();
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top