简体   繁体   English

使用DataContractJsonSerializer对JSON对象进行部分反序列化

[英]Partial deserialization of JSON object by using DataContractJsonSerializer

As a response from a Bitbucket REST API I'm getting the following JSON object (simplified version): 作为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"
    }
}

The only part from this JSON object I need to be deserialized is a user part. 我需要反序列化这个JSON对象的唯一部分是user部分。 For that purposes I created the following class: 为此,我创建了以下类:

[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; }
}

And a helper method to deserialize json: 以及一个反序列化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;
    }
}

So, when I'm trying to get deserialized User object by using this code: 所以,当我试图通过使用此代码获取反序列化的User对象时:

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

Then I'm getting user object created containing all properties as null . 然后我将创建包含所有属性为null user对象。 I have tried to find right attributes to use on class header, but the result is same. 我试图找到在类头上使用的正确属性,但结果是一样的。 And also I'm not using a Json.NET library just to avoid extra library reference as well as I'm not creating wrapper class to hold that user object as property of User type and repositores object as a array of the Repositories[] type. 而且我也没有使用Json.NET库来避免额外的库引用以及我没有创建包装类来将该用户对象保存为User类型的属性并将对象重新存储为Repositories []类型的数组。 Is there a solution for this issue to get deserialized user object without null fields ? 是否有解决此问题的方法来获取没有空字段的反序列化用户对象?

Your code doesn't work, because the JSON object you're deserializing doesn't have any of the User properties. 您的代码不起作用,因为您要反序列化的JSON对象没有任何User属性。 The deserializer certainly won't try looking into children of the current object to see if something matches. 反序列化器肯定不会尝试查看当前对象的子项以查看是否匹配。

What you should do is to create a type that represents the whole response object. 您应该做的是创建一个表示整个响应对象的类型。 If you're not interested in the repositories part, then just omit it. 如果您对repositories部分不感兴趣,那么只需省略它。

The following code works for me: 以下代码适用于我:

[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;
}

I am writing a code for you it will help you to deserialize the object from json to yourClassCustomObject. 我正在为您编写代码,它将帮助您将对象从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;
   }
} 

Above code is working in my wp8 application it is faster you can try, it will help you. 上面的代码在我的wp8应用程序中工作,你可以尝试更快,它会帮助你。 I am performing asynchronous operation but you can create your simple method with BitbucketUser return type. 我正在执行异步操作,但您可以使用BitbucketUser返回类型创建简单方法。

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

相关问题 在C#中使用DataContractJsonSerializer反序列化JSON对象 - Deserialization of JSON object by using DataContractJsonSerializer in C# 在 C# 中使用 DataContractJsonSerializer 使用 List&lt;&gt; 反序列化 JSON 对象 - Deserialization of JSON object with List<> using DataContractJsonSerializer in C# 使用C#中的DataContractJsonSerializer将子字段作为字符串反序列化JSON对象 - Deserialization of JSON object with sub field as string using DataContractJsonSerializer in C# DataContractJsonSerializer动态对象反序列化 - DataContractJsonSerializer dynamic object deserialization 使用DataContractJsonSerializer,将JSON字符串反序列化为具有列表和接口作为属性的C#对象 - Using DataContractJsonSerializer, deserialization of JSON string into C# object which has list & interface as properties 从 JSON 反序列化部分对象 - Partial object deserialization from JSON 无法使用DataContractJsonSerializer将对象序列化为JSON - Unable to Serialize Object to JSON Using DataContractJsonSerializer 使用DataContractJsonSerializer设置JSON对象root - Set JSON object root using DataContractJsonSerializer 使用DataContractJsonSerializer作为JSON数组序列化对象 - Serialize an object using DataContractJsonSerializer as a json array 使用 DataContractJsonSerializer 将字典序列化为 JSON 对象 - Serialize a Dictionary as JSON object using DataContractJsonSerializer
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM