简体   繁体   English

如何将 Json 转换为 object c# 到发布数据 Z61D8A333F397D840BAB7D0DCD5A3426

[英]How to Convert Json to object c# To Post Data APi

{
    "user": {
        "id": 121,
        "username": "luckygirl3",
        "counter_rechecking": 0,
        "user_id": 76,
        "f_Id": "4334"
    }
}

How to convert it to object and post it to api.如何将其转换为 object 并将其发布到 api。 I have already know how to post but I need to post user object with parameters.我已经知道如何发布,但我需要发布带有参数的user object。 I tried this:我试过这个:

JObject jobjects = new JObject();
JObject jobjectss = new JObject();
jobjects["user"] = jobjectss;
jobjectss["id"] = 121;
jobjectss["username"] = "luckygirlx3";
jobjectss["counter_rechecking"] = 0;
jobjectss["user_id"] = 76;
jobjectss["f_Id"] = "4334";

How to Convert Json to object c# To Post Data APi如何将 Json 转换为 object c# 到发布数据 Z61D8A333F397D840BAB7D0DCD5A3426

This seems like you want to convert a JSON response to a object.这似乎您想将 JSON 响应转换为 object。 If this is the case then you want to deserialize your JSON.如果是这种情况,那么您需要反序列化您的 JSON。 You havn't posted your Post Data code, so I can't help much with that.你还没有发布你的Post Data代码,所以我对此无能为力。

I would first map your JSON to classes:我会先 map 你的 JSON 上课:

public class User
{
    public int Id { get; set; }
    public string Username { get; set; }
    [JsonProperty("counter_rechecking")]
    public int CounterRechecking { get; set; }
    [JsonProperty("user_id")]
    public int UserId { get; set; }
    [JsonProperty("f_id")]
    public string FId { get; set; }
}

public class RootObject
{
    public User User { get; set; }
}

Then deserialize your JSON to RootObject with Json.NET :然后使用Json.NET 将您的 JSON 反序列化为 RootObject RootObject

var deserializedJson = JsonConvert.DeserializeObject<RootObject>(json);

You can then access your properties like this:然后,您可以像这样访问您的属性:

Console.WriteLine(deserializedJson.User.Id);
Console.WriteLine(deserializedJson.User.Username);
Console.WriteLine(deserializedJson.User.CounterRechecking);
Console.WriteLine(deserializedJson.User.UserId);
Console.WriteLine(deserializedJson.User.FId);

I used JsonProperty to map your attributes with _ to nicer property members.我使用JsonProperty来 map 你的属性和_到更好的属性成员。 This is optional however.然而,这是可选的。

You can also use something like json2csharp.com or Edit -> Paste Sepcial -> Paste JSON as classes inside Visual Studio after copying your JSON to the clipboard to generate the classes for you.您还可以使用json2csharp.comEdit -> Paste Sepcial -> Paste JSON 作为 Visual Studio 中的类,然后将 Z0ECD11C1D7A287401D148A23BBD7A2F8 复制到剪贴板以生成剪贴板。

Full demo at dotnetfiddle.net . dotnetfiddle.net上的完整演示。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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