vladimirg
vladimirg

Reputation: 72

JavaScriptSerializer.deserialize json string separated by comma to list<string>

I've following type

class ToDoElement{


 public int id;
    public string title;
    public string description;
    public List<string> tags;
}

And also i have some json string:

string msg = "{"title":"someTitle", "description":"someDescription", "tags": "tag1, tag2, tag3"}

When i'm trying to parse it by JavaScriptSerializer:

System.Web.Script.Serialization.JavaScriptSerializer js = new System.Web.Script.Serialization.JavaScriptSerializer ();
ToDoElement o = js.Deserialize<ToDoElement> (msg);

I'm getting exception

"Cannot convert string to List".

What i'm doing wrong?

Upvotes: 3

Views: 5709

Answers (2)

dbc
dbc

Reputation: 116795

tags is just a string with comma separated words inside:

 "tags": "tag1, tag2, tag3"

You would need to deserialize into the following field:

 public string tags;

Later, you could split then with string.Split() and string.Trim().

If you still want a list of tags to appear in your classes, you could deserialize the "tags" property as a proxy property, like so:

class ToDoElement
{
    public int id;
    public string title;
    public string description;
    public string tags
    {
        get
        {
            if (TagList == null)
                return null;
            return string.Join(", ", TagList.ToArray());
        }
        set
        {
            if (value == null)
            {
                TagList = null;
                return;
            }
            TagList = value.Split(',').Select(s => s.Trim()).ToList();
        }
    }
    [ScriptIgnore]
    public List<string> TagList { get; set; }
}

Upvotes: 2

Yuval Itzchakov
Yuval Itzchakov

Reputation: 149538

This:

"tags": "tag1, tag2, tag3"

Isn't a proper JSON array, it should look like this:

"tags: ["tag1", "tag2", "tag3"]

If you can't change your JSON, you'll need to parse it into an intermediate object. I'm going to be using Json.NET for this example:

dynamic intermediateObj = JsonConvert.DeserializeObject<dynamic>(msg); 
ToDoElement = new ToDoElement 
{
    Title = intermediateObj.title,
    Description = intermediateObj.description,
    Tags = intermediateObj.tags.Split(',').Select(str => str.Trim())
                                          .ToList();
}

Note I've added the string.Trim call as well. You can remove it if not needed.

Upvotes: 3

Related Questions