简体   繁体   中英

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'
}

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.
]
}

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}}]
}

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM