简体   繁体   English

Newtosoft,PCL和Xamarin.Droid

[英]Newtosoft, PCL & Xamarin.Droid

I'am facing to a strange problem. 我正面临一个奇怪的问题。

I have a generic code that's was in my PCL project. 我的PCL项目中有一个通用代码。 This code is currently perferctly working in my windows phone project, but not in the android one. 这段代码目前在我的Windows Phone项目中正常运行,但是在android系统中却没有。

Here the code : ( the method that have the problem is CreateListFriend ) 这里的代码:(有问题的方法是CreateListFriend)

public class Friend : IFriend<User>
    {
        public int Id { get; set; }
        public string UserId { get; set; }
        public virtual User User { get; set; }

        private static volatile Friend instance;
        private static object syncRoot = new Object();

        private Friend() { }

        public static Friend Instance
        {
            get
            {
                if (instance == null)
                {
                    lock (syncRoot)
                    {
                        if (instance == null)
                            instance = new Friend();
                    }
                }

                return instance;
            }
        }


        /// <summary>
        /// Populate friend instance
        /// </summary>
        /// <param name="json">Json friend string</param>
        public void PopulateFriend(string json)
        {
            if (!String.IsNullOrEmpty(json))
            {
                var resultObj = JsonConvert.DeserializeObject<Friend>(json);
                Friend.Instance.Id = resultObj.Id;
                Friend.Instance.UserId = resultObj.UserId;
            }
        }

        /// <summary>
        /// Create friend list from json
        /// </summary>
        /// <param name="json">json string</param>
        /// <returns>friend list</returns>
        public List<Friend> CreateListFriend(string json)
        {
            List<Friend> resultObj = new List<Friend>();
            if (!String.IsNullOrEmpty(json))
            {
                resultObj = JsonConvert.DeserializeObject<List<Friend>>(json);
            }

            return resultObj;

        }
    }

在此处输入图片说明

As you can see in the previous picture, Json.net is able to "deserialize" but the object friend donc have the correct "fields".... 如上图所示,Json.net可以“反序列化”,但是对象朋友donc具有正确的“字段”。

I already tried to supress the class and recreate it... I already created a structure with the same fields, and all json deserialize it correctly, but i don't want to do it by this way. 我已经尝试抑制该类并重新创建它...我已经创建了一个具有相同字段的结构,并且所有json都正确地反序列化了它,但是我不想这样做。

Is somebody have an idea... 有人有主意吗?

Let's assume we have two JSON source file: 假设我们有两个JSON源文件:

friend.json: friend.json:

{
    "id": 5,
    "userId": 6
}

friends.json: friends.json:

[
    {
        "id": 1,
        "userId": 2
    },
    {
        "id": 2,
        "userId": 3
    },
    {
        "id": 3,
        "userId": 4
    },
    {
        "id": 4,
        "userId": 5
    }
]

We also have the Friend class. 我们也有Friend类。 Based on your example your class is a POCO for Entity Framework. 根据您的示例,您的课程是针对实体框架的POCO。 JsonProperty attribute is not needed if the source file has the same property names as your class. 如果源文件的属性名称与您的类相同,则不需要JsonProperty属性。

Note: I did not define any constructor for Friend class so it will have only one public parameterless constructor by default. 注意:我没有为Friend类定义任何构造函数,因此默认情况下它将只有一个公共的无参数构造函数。

public class Friend
{
    [JsonProperty("id")]
    public int Id { get; set; }

    [JsonProperty("userId")]
    public string UserId { get; set; }

    public virtual User User { get; set; }

    public override string ToString()
    {
        return String.Format("User: Id={0}; UserId={1}", Id, UserId);
    }
}

I would separate the logic for creating Friend instances. 我将分离创建Friend实例的逻辑。 Just for an example I create a FriendLoader class. 仅作为示例,我创建一个FriendLoader类。

public class FriendLoader
{
    public Friend LoadFriend(string jsonSource)
    {
        return String.IsNullOrEmpty(jsonSource) ? null : JsonConvert.DeserializeObject<Friend>(jsonSource);
    }

    public List<Friend> LoadFriends(string jsonSource)
    {
        var friends = new List<Friend>();

        if (!String.IsNullOrEmpty(jsonSource))
        {
            friends = JsonConvert.DeserializeObject<List<Friend>>(jsonSource);
        }

        return friends;
    }
}

Here is the console app to test the above code. 这是用于测试上述代码的控制台应用程序。

class Program
{
    static void Main(string[] args)
    {
        string friendJson = File.ReadAllText("friend.json");
        string friendsJson = File.ReadAllText("friends.json");

        var loader = new FriendLoader();

        var friend = loader.LoadFriend(friendJson);
        var friends = loader.LoadFriends(friendsJson);

        Console.WriteLine("One friend:");
        Console.WriteLine(friend);

        Console.WriteLine();

        Console.WriteLine("List of friends:");
        friends.ForEach(Console.WriteLine);
    }
}

Hope this helps. 希望这可以帮助。

By the way, could you please show the definition of your IFriend<T> interface? 顺便问一下,能否请您显示IFriend<T>接口的定义?

sorry for the delay I did not have the time this week to post. 抱歉,我本周没有时间发布。

This is not related to my class but to the android.platform. 这与我的课程无关,但与android.platform有关。

We just need to tell android platform to preserve all attribute with this : 我们只需要告诉android平台使用以下命令保留所有属性:

[Preserve(AllMembers = true)]

Thanks for your time :) 谢谢你的时间 :)

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

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