简体   繁体   English

如何在Windows Phone 7中进行Json? 无法使用动态关键字

[英]How to do Json in Windows Phone 7? Can't Use Dynamic Keyword

I am working with wp7 and even though when I type "dynamic" in VS highlights and lets me compile and run the application, but as soon as I try to use it I get compile errors. 我正在使用wp7,即使当我在VS高亮中键入“ dynamic”并允许我编译和运行应用程序时,但是一旦尝试使用它,就会出现编译错误。

I read I can't use dynamic keyword and now kinda lost on how to do my json parsing(I am using json.net and restsharp but both run into the same problem if I can't use dynamic) 我读到我不能使用dynamic关键字,现在有点迷失了如何进行json解析(我使用的是json.net和restsharp,但是如果我不能使用dynamic的话,它们都会遇到相同的问题)

For example say if I use foursquare api. 例如说如果我使用foursquare api。 All json data is always returned like 所有json数据总是像

 {
          "meta": {
            "code": 200,
             ...errorType and errorDetail...
          },
          "notifications": {
             ...notifications...
          },
          "response": {
             ...results...
          }
        }

but the response will have different data. 但是响应将具有不同的数据。 For instance it might have user data(User Class) or it might have venue data(Venue class). 例如,它可能具有用户数据(用户类别),或者可能具有场所数据(场地类别)。

The bottom line though is I am going to need a class called Response that is in a RootObject class. 但最重要的是,我将需要RootObject类中的一个名为Response的类。

But I can't have the same class name(unless I start putting them in different name spaces but not crazy about that idea). 但是我不能使用相同的类名(除非我开始将它们放在不同的名称空间中,但不要对这个想法感到疯狂)。

Only other thing I can think of what sucks too is 我能想到的唯一的另一件事就是

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

public class Response
{
    public User User { get; set; }
    public List<Venue> Venues { get; set; }
}

This response object will in the end have all the different classes that could come back and in reality only property in the Response object will probably be filled. 最后,此响应对象将具有所有可能返回的所有不同类,实际上,只有响应对象中的属性可能会被填充。

Is there a better way? 有没有更好的办法?

Alright it took me forever to get a sample together (I hate OAuth), but you can use the JsonConverter with an interface to parse the responses. 好吧,我花了永远的JsonConverter来收集样本(我讨厌OAuth),但是您可以将JsonConverter与接口一起使用来解析响应。

See: 看到:

Here is an example for the User and Venues : 这是用户场所的示例:

Converter: 转换器:

public class ResponseConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return (objectType == typeof(IResponse));
    }

    public override object ReadJson(JsonReader reader,
                                    Type objectType,
                                    object existingValue,
                                    JsonSerializer serializer)
    {
        // reader is forward only so we need to parse it
        var jObject = JObject.Load(reader);

        if(jObject["user"] != null)
        {
            var user = jObject.ToObject<UserResponse>();
            return user;
        }

        if(jObject["venues"] != null)
        {
            var venue = jObject.ToObject<VenuesResponse>();
            return venue;
        }

        throw new NotImplementedException("This reponse type is not implemented");
    }

    public override void WriteJson(JsonWriter writer,
                                   object value,
                                   JsonSerializer serializer)
    {
        // Left as an exercise to the reader :)
        throw new NotImplementedException();
    }
}

DTO: DTO:

public class ApiRespose
{
    public ApiRespose()
    {
        Notifications = new List<Notification>();
    }

    [JsonProperty("meta")]
    public Meta Meta { get; set; }

    [JsonProperty("notifications")]
    public List<Notification> Notifications { get; set; }

    [JsonProperty("response")]
    [JsonConverter(typeof(ResponseConverter))]
    public IResponse Response { get; set; }
}

public interface IResponse
{
}

public class UserResponse : IResponse
{
    [JsonProperty("id")]
    public string Id { get; set; }

    [JsonProperty("firstname")]
    public string FirstName { get; set; }

    [JsonProperty("lastname")]
    public string LastName { get; set; }
    // Other properties
}

public class VenuesResponse : IResponse
{
    public VenuesResponse()
    {
        Venues = new List<Venue>();
    }

    [JsonProperty("venues")]
    public List<Venue> Venues { get; set; }
}

public class Venue
{
    [JsonProperty("id")]
    public string Id { get; set; }

    [JsonProperty("name")]
    public string Name { get; set; }
    // Other Properties
}

public class Meta
{
    [JsonProperty("code")]
    public int Code { get; set; }
}

public class Notification
{
    [JsonProperty("type")]
    public string Type { get; set; }

    [JsonProperty("item")]
    public Item Item { get; set; }
}

public class Item
{
    [JsonProperty("unreadcount")]
    public int UnreadCount { get; set; }
}

Usage: 用法:

string jsonData = GetJsonData();

var apiResponse = JsonConvert.DeserializeObject<ApiResponse>(json);

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

相关问题 如何在Windows Phone 7上解析JSON到动态对象? - How to parse JSON to a dynamic object on Windows Phone 7? 无法下载Json Array Windows Phone - Can't Download Json Array Windows phone Windows Phone 7是否支持动态关键字? - Does Windows Phone 7 support the dynamic keyword? 为Windows Phone反序列化动态json - deserializing dynamic json for windows phone Windows Phone如何使用.pls格式? - How can the windows phone use the .pls format? 如何使用Windows Phone和Selenium? - How I can use Windows Phone and Selenium? 仅在Windows Phone上无法读取具有值的json数组 - Can't read json array with value only on Windows phone 为什么我在使用Microsoft.Bcl时不能在Windows Phone 7.1 MvvmCross项目中使用await关键字 - 无法等待&#39;System.Threading.Tasks.Task? - Why can't I use await keyword in my Windows Phone 7.1 MvvmCross project while using the Microsoft.Bcl - cannot await 'System.Threading.Tasks.Task? 这是否正确使用dynamic关键字来返回JSON数据 - Is this a proper use of dynamic keyword for returning JSON data 我无法使用Windows Phone 8.1的IsolatedStorageSettings - I can't use IsolatedStorageSettings for windows phone 8.1
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM