2014-02-12 114 views
0

我試圖反序列化JSON字符串接口實例,如何使用Json.Net反序列化?

,但我的代碼返回類似 「異常消息無法創建鍵入Form1 +的IFoo的一個實例。 Type是一個接口或抽象類,不能實例化。路徑'值'

但是我不能做的任何事情?,我想解決這種情況,謝謝。

這裏是代碼

public interface IFoo 
    { 
     int value { get; } 
    } 

    [Serializable] 
    public class Foo : IFoo 
    { 
     public int value 
     { 
      get { return 1; } 
     } 
    } 

    public void run() 
    { 
     IFoo foo = new Foo(); 

     string json = JsonConvert.SerializeObject(foo); //it's working 
     IFoo dese = JsonConvert.DeserializeObject<IFoo>(json); //but it's not working 
    } 
+0

什麼是錯的'IFoo的DESE = JsonConvert.DeserializeObject (JSON);' –

回答

1

錯誤信息很簡單,它要求你不給它的接口。 '無法創建Form1 + IFoo類型的實例。 Type是一個接口或抽象類,不能實例化。路徑'值'

請嘗試此操作。

var dese = JsonConvert.DeserializeObject<Foo>(json) 
+0

@ L.B,感謝您指出了這一點,我已經刪除了部分違規 – Yohannes

1

因爲接口或抽象類,不能被實例化 你可以試試這個

IFoo dese = JsonConvert.DeserializeObject<IFoo>(json); //but it's not working 
Foo dese = JsonConvert.DeserializeObject<Foo>(json); //it'sworking 
2

由於接口和抽象類不能被實例化。你應該使用這個,

 IFoo dese = JsonConvert.DeserializeObject<Foo>(json);