I copy from XML to JSON response code 2

enter the link description here

public static class SerializeExtension { public static DataContractJsonSerializer JSON_SerializeObjToDCJS(this object obj) { var ser_json = new DataContractJsonSerializer(obj.GetType()); return ser_json; } public static void JSON_SerializeObjToFile(this object obj, string filename) { var ser_json = new DataContractJsonSerializer(obj.GetType()); using (FileStream fs = new FileStream(filename, FileMode.Create)) { ser_json.WriteObject(fs, obj); } } public static void JSON_DeSerializer1() { using (FileStream fs = new FileStream("save_json.json", FileMode.OpenOrCreate)) { JSON_DeserializeFileStream(fs); } } public static T JSON_DeserializeFileStream<T>(this FileStream fs) { var ser_json = new DataContractJsonSerializer(typeof(T)); var deser_json = (T)ser_json.ReadObject(fs); return (T)deser_json; } 

On line

 JSON_DeserializeFileStream(fs); 

"SerializeExtension.JSON_DeserializeFileStream (FileStream)" cannot be determined by use. Try to explicitly define type arguments.

  • one
    Obviously. How does the compiler know what type T should be? - VladD
  • one
    You must know in advance which type you are deserializing. Stencil magic doesn't know that either. - VladD

1 answer 1

fixed

 JSON_DeSerializer<Info>("save_json.json"); public static void JSON_DeSerializer<T>(string filename) { using (FileStream fs = new FileStream(filename, FileMode.OpenOrCreate)) { JSON_DeserializeFileStream<T>(fs); } } 

Now on var deser_json = (T) ser_json.ReadObject ( fs );

ReadTimeout = "fs.ReadTimeout" threw an exception of type "System.InvalidOperationException"

WriteTimeout = "fs.WriteTimeout" threw an exception of type "System.InvalidOperationException"

 public static T JSON_DeserializeFileStream<T>(this FileStream fs) { var ser_json = new DataContractJsonSerializer(typeof(T)); var deser_json = (T)ser_json.ReadObject(fs); return deser_json; } 

It turned out the file is empty.

 var obj = Info.NewInfo(); var filename = "save_json.json"; JSON_SerializeObjToFile(obj, filename); var result = JSON_DeSerializer<Info>("save_json.json"); 
  • one
    It is unlikely that you are from FileStream but really want to read the serialized FileStream . - VladD
  • @VladD, but can FileStream be so serialized / deserialized at all? - Grundy
  • Inside the function T should be used and not Info , otherwise only it will be able to deserialize and then the meaning in the generic is lost - Grundy
  • @Grundy: Something tells me that no. - VladD