Search code examples
c#jsonstringjavascriptserializer

How to convert a json string?


Can't seem to get this working. I have this json string and I want to convert it to a C# object:

{"name":"mousePos","args":[{"mouseDet":{"rid":"1","posx":1277,"posy":275}}]}

I've been trying JavaScriptSerializer but I'm having no luck. I'm unsure how to get the values of posx and posy. Can anyone suggest how I would do this? Thanks for the help.

EDIT:

public class JsonData
{
    public string name { get; set; }
}
public Form1()
{
    // ---- Other stuff here ----

    string json = data.MessageText; // The json string.

    JavaScriptSerializer ser = new JavaScriptSerializer();
    JsonData foo = ser.Deserialize<JsonData>(json);


    MessageBox.Show(foo.name); // Shows 'mousePos'
}

Solution

  • You just need to extend out your object model a little bit to cover it. Based on what you've got in your example, it would be something like:

    public class JsonData
    {
        public string name { get; set; }
        public Arguments[] args { get; set; }
    }
    
    public class Arguments
    {
        public MouseDet mouseDet { get; set; }
    }
    
    public class MouseDet
    {
        public int rid { get; set; }
        public int posx { get; set; }
        public int posy { get; set; }
    }
    
    ...
    
    var posx = foo.args[0].mouseDet.posx;