2016-06-04 4 views
0

나는 이상한 문제에 직면 해있다.Newtosoft, PCL & Xamarin.Droid

내 PCL 프로젝트에있는 일반적인 코드가 있습니다. 이 코드는 현재 내 Windows Phone 프로젝트에서 일하고 있지만 Android 용으로는 제대로 작동하지 않습니다. 여기

코드 : (문제가 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; 

     } 
    } 

enter image description here

이전 그림에서 볼 수 있듯이, Json.net는 "직렬화"하지만 할 수있는 개체 친구 donc 올바른 "필드"를 가지고 ....

나는 이미 클래스를 억제하고 그것을 다시 만들려고 노력했다 ... 나는 동일한 필드를 가진 구조를 이미 만들었고, 모든 json은 올바르게 deserialize하지만 나는 해야 할 것 이런 식으로하고 싶지 않습니다.

friend.json :

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

friends.json :

+0

왜'Friend' 클래스는 싱글 톤에 대한

[Preserve(AllMembers = true)] 

감사합니다? 싱글 톤 (singleton)의 목록은 싱글 톤 (singleton)이 '친구 (Friend)'인스턴스를 하나만 갖고 싶어한다는 것을 의미하기 때문에 저에게 의미가 없습니다. 왜 그것이 필요한지 명확히 설명해 주시겠습니까? 추가로 - 내가 아는 한 - JsonConvert는 public 생성자가 필요하고 여러분은 그것을 private으로 정의한다. 하지만 개인 생성자에서 작동하는 경우 문제는 싱글 톤을 사용하고 모든 목록 항목이 마지막으로 deserialized 된 인스턴스가 될 수 있습니다. – Gabor

+0

답장을 보내 주셔서 감사합니다. 친구의 싱글 톤은 내가 변하지 않는 아키텍처 실수였습니다. 친구 싱글 톤을 삭제하지만 지금은이 오류가 있습니다 "Newtonsoft.Json.JsonSerializationException : Cheer_up_app.Model.Friend 유형에 사용할 생성자를 찾을 수 없습니다. 클래스에 기본 생성자, 인수가있는 생성자 또는 생성자가 표시되어 있어야합니다. JsonConstructor 특성을 사용하십시오. 경로 '[0]. 사용자', 줄 1, 위치 9 " – OrcusZ

답변

0

이의 우리가이 개 JSON 소스 파일을 가정 해 봅시다 ... 누군가가 아이디어가인가
[ 
    { 
     "id": 1, 
     "userId": 2 
    }, 
    { 
     "id": 2, 
     "userId": 3 
    }, 
    { 
     "id": 3, 
     "userId": 4 
    }, 
    { 
     "id": 4, 
     "userId": 5 
    } 
] 

우리는 또한 Friend 클래스를 가지고 있습니다. 예제를 기반으로 클래스는 Entity Framework 용 POCO입니다. 원본 파일의 클래스 이름이 속성 이름과 동일하면 JsonProperty 특성이 필요하지 않습니다.

참고 :Friend 클래스의 생성자를 정의하지 않았으므로 기본적으로 매개 변수없는 public 생성자가 하나만 있습니다.

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

나는 Friend 인스턴스를 생성하는 로직을 분리하는 것입니다. 예를 들어 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; 
    } 
} 

다음은 위 코드를 테스트하는 콘솔 앱입니다.

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

희망이 있습니다.

그런데 IFriend<T> 인터페이스의 정의를 보여 주실 수 있습니까?

0

지연을 위해 죄송합니다. 이번 주에 게시 할 시간이 없었습니다.

이것은 내 수업과 관련이 없지만 android.platform과 관련이 있습니다.

우리는이 모든 속성을 보존하기 위해 안드로이드 플랫폼을 알려줄 필요가 : 시간 :