0

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'
}
John Saunders
  • 160,644
  • 26
  • 247
  • 397
Joey Morani
  • 25,431
  • 32
  • 84
  • 131

3 Answers3

1

I dropped that into JsonLint and got an error. Its invalid JSON

{
    "name": "mousePos",
    "args": [
        "mouseDet": {
            "rid": "1",
            "posx": 1277,
            "posy": 275
        }
    }    //-- THIS should not be here.
]
}
Jason Kulatunga
  • 5,814
  • 1
  • 26
  • 50
0

The reason the JSON is not valid is because your "args" property contains a key/value pair inside of square brackets, which is not a valid array. I'm guessing it should be something like:

{
    "name":"mousePos",
    "args":[{"mouseDet":{"rid":"1","posx":1277,"posy":275}}]
}
Joe Enos
  • 39,478
  • 11
  • 80
  • 136
0

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;
Joe Enos
  • 39,478
  • 11
  • 80
  • 136