【问题标题】:using DataContractJsonSerializer when Json object propety is named with "@" symbol当 Json 对象属性以“@”符号命名时使用 DataContractJsonSerializer
【发布时间】:2015-02-25 02:00:04
【问题描述】:

在使用 DataContractJsonSerializer 解析 json 响应时,我遇到了一个属性名为 @id 的 json 对象,我似乎无法填充此字段。所有其他字段都没有问题地填充。我什至可以使用 Fiddler 填充此字段,但不能使用 DataContractJsonSerializer。我的代码如下...

        public IEnumerable<Vehicle> vehicles { get; set; }

    public async Task GetVehicleList(string access_token)
    {
        vehicles = await GetVehicleListInfo(access_token);
    }

    private async Task<IEnumerable<Vehicle>> GetVehicleListInfo(string access_token)
    {
        using (var client = new HttpClient())
        {
            client.BaseAddress = new Uri("https://www.example.com/");
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/vnd.example.api-v1+json"));
            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer" + access_token);

            HttpResponseMessage response = await client.GetAsync("vehicles");

            //IEnumerable<Vehicle> vehicles = new IEnumerable<Vehicle>();
            Vehicle vehicle = new Vehicle();
            PagedVehicleResult pvr = new PagedVehicleResult();
            Stream dataStream = null;

            if (response.IsSuccessStatusCode)
            {
                dataStream = await response.Content.ReadAsStreamAsync();
                DataContractJsonSerializer serializer = new DataContractJsonSerializer(pvr.GetType());
                pvr = (PagedVehicleResult)serializer.ReadObject(dataStream);
            }
            vehicles = pvr.vehicle;
            return vehicles;
        }
    }
}


/// <summary>
/// parent object returned by json.  contains list of vehicle objects
/// </summary>
public class PagedVehicleResult
{
    public int count { get; set; }
    public int index { get; set; }
    public int limit { get; set; }
    public int total { get; set; }
    public string type { get; set; }
    public IEnumerable<Vehicle> vehicle { get; set; }
}
public class Vehicle
{
    public int id { get; set; }  //This is the property in question.  
//When it comes back in fiddler it looks like "@id", and it does get populated.
//when it comes back in my console application it is 0 if int and null if string.
    public string vin { get; set; }
    public string label { get; set; }
    public string color { get; set; }
    public string make { get; set; }
    public string model { get; set; }
    public string deviceSerialNumber { get; set; }
    public int year { get; set; } //consider making date?  unknown repercussions
    public CreateTimestamp createdTimestamp { get; set; } 
    public ModifiedTimestamp modifiedTimestamp { get; set; } 
}
public class CreateTimestamp
{
    public string readOnly { get; set; }
    public string value { get; set; } //had to cast as string.. can convert to datetime before database insert
}
public class ModifiedTimestamp
{
    public string readOnly { get; set; }
    public string value { get; set; }
}

如何将该 json @id 字段映射到我的 Vehicle 类 id 属性?

【问题讨论】:

    标签: asp.net json parsing httpwebresponse datacontractjsonserializer


    【解决方案1】:

    好的,我通过阅读有关该主题的各种不同帖子自己弄清楚了这一点。

    我所要做的就是先将其解析为 json 字符串,然后在字符串上调用 .replace() 来更改 id。然后我在上面使用了 JavaScriptSerializer,它起作用了。

                    if (response.IsSuccessStatusCode)
                {
                    dataStream = await response.Content.ReadAsStreamAsync();
    
                    string content;
                    using (StreamReader reader = new StreamReader(dataStream, true))
                    {
                        content = reader.ReadToEnd();
                        content = content.Replace("@id", "id");
                        JavaScriptSerializer js = new JavaScriptSerializer();                    
                        pvr = js.Deserialize<PagedVehicleResult>(content);
    
                    }                   
                }                
                vehicles = pvr.vehicle;
                return vehicles;
    

    现在,当我尝试时,我的对象 ID 已正确插入。

    【讨论】:

      猜你喜欢
      • 2023-02-21
      • 2021-12-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多