5

作为来自 Bitbucket REST API 的响应,我得到以下 JSON 对象(简化版):

{
    "repositories": [
        {
            "scm": "hg",
            "has_wiki": false,            
            "language": "c#",
            "slug": "Repo1"
        },
        {
            "scm": "hg",
            "has_wiki": false,            
            "language": "java",
            "slug": "Repo2"
        },
        {
            "scm": "hg",
            "has_wiki": true,            
            "language": "c#",
            "slug": "Repo3"
        }
    ],
    "user": {
        "username": "someuser",
        "first_name": "Some",
        "last_name": "User",
        "display_name": "Some User",
        "is_team": false,
        "avatar": "https://someuseravatar.com",
        "resource_uri": "/1.0/users/someuser"
    }
}

我需要反序列化的这个 JSON 对象的唯一部分是一个user部分。为此,我创建了以下类:

[DataContract(Name="user")]
public class BitbucketUser
{
    [DataMember(Name = "username")]
    public string Username { get; set; }

    [DataMember(Name = "first_name")]
    public string FirstName { get; set; }

    [DataMember(Name = "last_name")]
    public string LastName { get; set; }

    [DataMember(Name = "display_name")]
    public string DisplayName { get; set; }

    [DataMember(Name = "is_team")]
    public bool IsTeam { get; set; }

    [DataMember(Name = "avatar")]
    public string Avatar { get; set; }

    [DataMember(Name = "resource_uri")]
    public string ResourceUri { get; set; }
}

以及反序列化 json 的辅助方法:

public static T Deserialize<T>(string json)
{
    DataContractJsonSerializer deserializer = new DataContractJsonSerializer(typeof(T));
    using (MemoryStream stream = new MemoryStream(Encoding.Unicode.GetBytes(json)))
    {
        T result = (T)deserializer.ReadObject(stream);
        return result;
    }
}

因此,当我尝试User使用此代码获取反序列化对象时:

User user = JsonHelper.Deserialize<User>(jsonResponse);

然后我将user创建包含所有属性的对象作为null. 我试图找到在类头上使用的正确属性,但结果是一样的。而且我没有使用 Json.NET 库只是为了避免额外的库引用,也没有创建包装类来将该用户对象作为User类型的属性并将存储库对象作为 Repositories[] 类型的数组。这个问题是否有解决方案来获取没有空字段的反序列化用户对象?

4

2 回答 2

4

您的代码不起作用,因为您要反序列化的 JSON 对象没有任何User属性。反序列化器当然不会尝试查看当前对象的子对象以查看是否匹配。

您应该做的是创建一个代表整个响应对象的类型。如果您对该repositories部分不感兴趣,则忽略它。

以下代码适用于我:

[DataContract]
public class BitbucketResponse
{
    [DataMember(Name="user")]
    public BitbucketUser User { get; set; }
}

[DataContract]
public class BitbucketUser
{
    [DataMember(Name = "username")]
    public string Username { get; set; }

    // etc.
}

…

var serializer = new DataContractJsonSerializer(typeof(BitbucketResponse));
using (var stream = …)
{
    var response = (BitbucketResponse)serializer.ReadObject(stream);
    var user = response.User;
}
于 2013-11-18T17:06:34.967 回答
0

我正在为您编写代码,它将帮助您将对象从 json 反序列化为 yourClassCustomObject。

private async Task<List<BitbucketUser>> MyDeserializerFunAsync()
{
    List<BitbucketUser> book = new List<BitbucketUser>();
    try
    {
       //I am taking my url from appsettings. myKey is my appsetting key. You can write direct your url.
       string url = (string)appSettings["mykey"];
       var request = HttpWebRequest.Create(url) as HttpWebRequest;
       request.Accept = "application/json;odata=verbose";
       var factory = new TaskFactory();
       var task = factory.FromAsync<WebResponse>(request.BeginGetResponse,request.EndGetResponse, null);
       var response = await task;
       Stream responseStream = response.GetResponseStream();
       string data;
       using (var reader = new System.IO.StreamReader(responseStream))
       {
           data = reader.ReadToEnd();
       }
       responseStream.Close();
       DataContractJsonSerializer json = new DataContractJsonSerializer(typeof(List<BitbucketUser>));
       MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(data));
       book = (List<BitbucketUser>)json.ReadObject(ms);
       return book;
   }
} 

上面的代码在我的 wp8 应用程序中运行,你可以尝试更快,它会对你有所帮助。我正在执行异步操作,但您可以使用 BitbucketUser 返回类型创建您的简单方法。

于 2013-11-18T05:59:34.407 回答