2014-11-25 117 views
0

我正在使用JSON.Net反序列化JSON字符串。 JSON字符串是JSON.Net的反序列化返回'null'

string testJson = @"{ 
        ""Fruits"": { 
         ""Apple"": { 
          ""color"": ""red"", 
          ""size"": ""round""        
         }, 
         ""Orange"": { 
          ""Properties"": { 
           ""color"": ""red"", 
           ""size"": ""round"" 
          } 
         } 
        } 
       }"; 

和我的代碼是

public class Fruits 
{ 
    public Apple apple { get; set; } 
    public Orange orange { get; set; } 
} 

public class Apple 
{ 
    public string color { get; set; } 
    public string size { get; set; }    
} 

public class Orange 
{ 
    public Properties properties { get; set; } 
} 

public class Properties 
{ 
    public string color { get; set; } 
    public string size { get; set; } 
} 

我想用下面的代碼

Fruits result = JsonConvert.DeserializeObject<Fruits>(testJson); 

我在結果的問題,反序列化這個水果蘋果橙色null而不是他們的屬性,顏色,尺寸

+3

問題是最外層的'{...}'護腕對應着你的'Fruits'類型,'Fruits'不包含名爲'Fruits'的屬性。嘗試創建一個包含'Fruits'屬性的容器類型,並對其進行反序列化。 – 2014-11-25 13:54:28

+5

或者按照其他方式將某些內容序列化爲JSON以瞭解正確的格式。 – DavidG 2014-11-25 13:58:15

回答

3

假設你可以」 t改變json,你需要創建一個新的FruitsWrapper類,它具有Fruits屬性

public class FruitsWrapper 
{ 
    public Fruits Fruits { get; set; } 
} 

和反序列化JSON的成FruitsWrapper代替Fruits

FruitsWrapper result = JsonConvert.DeserializeObject<FruitsWrapper>(testJson); 

工作演示的實例:https://dotnetfiddle.net/nQitSD

+0

非常感謝,它效果很好。 – Gopichandar 2014-11-25 14:27:05

1

JSON字符串應該是:

string testJson = @"{ 
         ""Apple"": { 
          ""color"": ""red"", 
          ""size"": ""round""}, 
         ""Orange"": { 
          ""Properties"": { 
           ""color"": ""red"", 
           ""size"": ""round"" } 
           } 
        }"; 

與你的類

2

的問題是,在你的Json最外面的護腕相當於你試圖反序列化類型的反序列化。

所以這個:

string testJson = @"{ 
         ""Fruits"": { ... } 
        }"; 

對應於水果,因爲這是你嘗試反序列化的東西。

string testJson = @"{ 
         ""Fruits"": { ... } 
         ^--+-^ 
          | 
          +-- this is assumed to be a property of this --+ 
                      | 
               +------------------------+ 
               | 
               v--+-v 
Fruits result = JsonConvert.DeserializeObject<Fruits>(testJson); 

然而,Fruits類型不具有屬性命名Fruits,因此沒有什麼是反序列化。

如果JSON的不能改變,你需要創建你反序列化代替,像這樣的容器類型:

public class Container 
{ 
    public Fruits Fruits { get; set; } 
} 

然後你就可以反序列化:

Container result = JsonConvert.DeserializeObject<Container>(testJson); 
0

你JSON字符串不正確(如其他人指出的),但我加入這幫助您找到正確的格式。鑑於你有一個fruit對象是這樣的:

var fruit = new Fruits 
{ 
    apple = new Apple { color = "red", size = "massive" }, 
    orange = new Orange { properties = new Properties { color = "orange", size = "mediumish" } } 
}; 

然後可以連載這JSON:

var testJson = JsonConvert.SerializeObject(fruit); 

現在你可以看到串行輸出將是這樣的:(略格式化)

{"apple": 
    {"color":"red","size":"massive"}, 
"orange": 
    {"properties": 
     {"color":"orange","size":"mediumish"}}} 

,這將很容易deserialise回你的對象:

fruit = JsonConvert.DeserializeObject<Fruits>(testJson);