2016-10-24 11 views
0

私から、次のJSONを持っている:私はJSONをシリアライズおよびデシリアライズするためにC#MVCモデル+ Json.netを使用したいhttps://www.mywot.com/wiki/APIシリアライズ/デシリアライズWOT JSON API

{ 
    "google.com": { 
     "target": "google.com", 
     "0": [94, 73], 
     "1": [94, 73], 
     "2": [94, 73], 
     "4": [93, 67], 
     "categories": { 
      "501": 99, 
      "301": 48, 
      "304": 5 
     } 
    }, 
    "yahoo.com": { 
     "target": "yahoo.com", 
     "0": [94, 75], 
     "1": [94, 75], 
     "2": [94, 75], 
     "4": [93, 69], 
     "categories": { 
      "501": 99, 
      "301": 16, 
      "304": 11 
     } 
    } 
} 

。 私は次のモデルを試してみましたが、私は2つの問題を抱えて:

  1. Webサイト名が可変である(google.com、yahoo.com)
  2. カテゴリキーが数字(MVCモデルが許可していないですがキーとしての数字)。

public class Categories 
{ 
    public int 401 { get; set; } 
    public int 501 { get; set; } 
} 

public class Website 
{ 
    public string target { get; set; } 
    public List<int> 0 { get; set; } 
    public List<int> 1 { get; set; } 
    public List<int> 2 { get; set; } 
    public List<int> 4 { get; set; } 
    public Categories categories { get; set; } 
} 

public class RootObject 
{ 
    public Website domain_name { get; set; } 
} 

答えて

2

だからあなたのJSONは非常に汚れています。そして、0,1,2,3のような変数の名前を設定することはできません。 この場合、[JsonProperty("HERE_IS_PROPERTY_NAME")]属性が必要です。

jsonを動作させて解析するコードの下にあります。

class Program 
    { 
     static void Main(string[] args) 
     { 
      string json = "{\"google.com\":{\"target\":\"google.com\",\"0\":[94,73],\"1\":[94,73],\"2\":[94,73],\"4\":[93,67],\"categories\":{\"501\":99,\"301\":48,\"304\":5}},\"yahoo.com\":{\"target\":\"yahoo.com\",\"0\":[94,75],\"1\":[94,75],\"2\":[94,75],\"4\":[93,69],\"categories\":{\"501\":99,\"301\":16,\"304\":11}}}"; 

      Dictionary<string, dynamic> dictionary_data = JsonConvert.DeserializeObject<Dictionary<string, dynamic>>(json); 
      List<Website> sites = new List<Website>(); 
      foreach (var item in dictionary_data) 
      { 
       string data = Convert.ToString(item.Value); 
       data = data.Replace("\r\n", string.Empty); ; 
       Website site = JsonConvert.DeserializeObject<Website>(data); 
       sites.Add(site); 
      } 
     } 
    } 


    public class Categories 
    { 
     [JsonProperty("401")] 
     public int a { get; set; } 
     [JsonProperty("501")] 
     public int b { get; set; } 
    } 
    public class Website 
    { 
     public string target { get; set; } 

     [JsonProperty("0")] 
     public List<int> FirstList { get; set; } 

     [JsonProperty("1")] 
     public List<int> SecondList { get; set; } 

     [JsonProperty("2")] 
     public List<int> ThirdList { get; set; } 

     [JsonProperty("4")] 
     public List<int> FourList { get; set; } 
     public Categories categories { get; set; } 
    } 

    public class RootObject 
    { 
     public Website domain_name { get; set; } 
    } 
+0

ありがとう、それは良い答えです... – Yanga