/// <summary> /// JSON反序列化 /// <param name="strJson"></param> /// </summary> public static T DeserializeByDataContract <T>(string strJson) { if (string.IsNullOrEmpty(strJson)) { return(default(T)); } #if NET45 DataContractJsonSerializerSettings serializerSettings = new DataContractJsonSerializerSettings(); DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T), serializerSettings); #else DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T)); #endif using (MemoryStream memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(strJson))) { return((T)serializer.ReadObject(memoryStream)); } }
public Batch(string fname, Config cfg) { chnd = cfg; if (File.Exists(fname)) { FileStream input = File.OpenRead(fname); Console.WriteLine("+ processing batch file: {0}", fname); DataContractJsonSerializerSettings settings = new DataContractJsonSerializerSettings { UseSimpleDictionaryFormat = true }; var serializer = new DataContractJsonSerializer(typeof(BatchDefinition), settings); bdef = serializer.ReadObject(input) as BatchDefinition; foreach (KeyValuePair <string, string> item in bdef.options) { Console.WriteLine("~ batch option: {0} {1}", item.Key, item.Value); } } }
public static string Serialize <T>(T objectToSerialize) { using (MemoryStream memStm = new MemoryStream()) { DataContractJsonSerializerSettings settings = new DataContractJsonSerializerSettings(); settings.UseSimpleDictionaryFormat = true; var serializer = new DataContractJsonSerializer(typeof(T), settings); serializer.WriteObject(memStm, objectToSerialize); memStm.Seek(0, SeekOrigin.Begin); using (var streamReader = new StreamReader(memStm)) { string result = streamReader.ReadToEnd(); return(result); } } }
public static T Deserialize <T>(string jsonStringToDeserialize) { if (string.IsNullOrEmpty(jsonStringToDeserialize)) { throw new ArgumentException("jsonStringToDeserialize must not be null"); } MemoryStream ms = null; ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonStringToDeserialize)); DataContractJsonSerializerSettings settings = new DataContractJsonSerializerSettings(); settings.DateTimeFormat = new System.Runtime.Serialization.DateTimeFormat("yyyy-MM-ddTHH:mm:ss"); DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T), settings); return((T)serializer.ReadObject(ms)); }
//public static string ReadStringFromLocalFileOld(string filename) //{ // try // { // // reads the contents of file 'filename' in the app's local storage folder and returns it as a string // // access the local folder // StorageFolder local = Windows.Storage.ApplicationData.Current.LocalFolder; // // open the file 'filename' for reading // Stream stream = local.OpenStreamForReadAsync(filename).Result; // string text = ""; // // copy the file contents into the string 'text' // using (StreamReader reader = new StreamReader(stream)) // { // text = reader.ReadToEnd(); // } // return text; // } // catch (Exception ex) // { // System.Diagnostics.Debug.WriteLine("Error reading file: " + ex.Message); // return null; // //swallow throw; // } //} public static string SerializeJSonSprinkProg(SprinklerProgram t) { try { MemoryStream stream = new MemoryStream(); DataContractJsonSerializer ds = new DataContractJsonSerializer(typeof(SprinklerProgram)); DataContractJsonSerializerSettings s = new DataContractJsonSerializerSettings(); ds.WriteObject(stream, t); string jsonString = Encoding.UTF8.GetString(stream.ToArray()); //stream.Close(); return(jsonString); } catch (Exception ex) { return(ex.ToString()); //throw; } }
public static CovidScenario LoadFromFile(FileInfo file) { if (!file.Exists) { Log.Error($"The scenario file {file.FullName} does not exist."); throw new FileNotFoundException("Cannot find scenario file", file.FullName); } using var fileStream = file.Open(FileMode.Open); var settings = new DataContractJsonSerializerSettings { DateTimeFormat = new DateTimeFormat("o") }; var deserializer = new DataContractJsonSerializer(typeof(CovidScenario), settings); return((CovidScenario)deserializer.ReadObject(fileStream)); }
public static T JsonDeserialize <T>(string json, string dateFormat = "yyyy-MM-dd'T'HH:mm:ss'Z'") { try { using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(json))) { var settings = new DataContractJsonSerializerSettings() { DateTimeFormat = new DateTimeFormat(dateFormat), UseSimpleDictionaryFormat = true, }; DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T), settings); return((T)serializer.ReadObject(ms)); } } catch (Exception ex) { Logger.Log(ex); } return(default(T)); }
private void storeAnalogPattern(string dataStoreFilePath, MOTMasterSequence sequence) { Dictionary <String, Dictionary <Int32, Double> > analogPatterns = sequence.AnalogPattern.AnalogPatterns; var settings = new DataContractJsonSerializerSettings(); settings.UseSimpleDictionaryFormat = true; // Make format of json file {key : value} instead of {"Key": key, "Value": value} DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(Dictionary <String, Dictionary <Int32, Double> >), settings); TextWriter output = File.CreateText(dataStoreFilePath); using (MemoryStream ms = new MemoryStream()) { serializer.WriteObject(ms, analogPatterns); output.Write(Encoding.Default.GetString(ms.ToArray())); output.Close(); } }
public string Obj2Json(object obj, Type[] knownTypes) { DataContractJsonSerializerSettings settings = new DataContractJsonSerializerSettings(); settings.IgnoreExtensionDataObject = true; settings.EmitTypeInformation = EmitTypeInformation.AsNeeded; settings.KnownTypes = knownTypes; var x = new DataContractJsonSerializer(obj.GetType(), settings); var mem = new MemoryStream(); x.WriteObject(mem, obj); StreamReader sr = new StreamReader(mem); mem.Position = 0; string ret = sr.ReadToEnd(); return(ret); }
public static T Deserialize <T>(string json) { if (!string.IsNullOrEmpty(json)) { byte[] jsonBytes = Encoding.UTF8.GetBytes(json); using (var ms = new MemoryStream(jsonBytes)) { var settings = new DataContractJsonSerializerSettings() { DateTimeFormat = new System.Runtime.Serialization.DateTimeFormat("yyyy-MM-dd'T'HH:mm:ssZ"), KnownTypes = Assembly.GetExecutingAssembly().DefinedTypes }; var serializer = new DataContractJsonSerializer(typeof(T)); return((T)serializer.ReadObject(ms)); } } return(default(T)); }
internal T DeSerialiseObject <T>(string jsonString) { T output; DataContractJsonSerializerSettings settings = new DataContractJsonSerializerSettings(); settings.DateTimeFormat = new System.Runtime.Serialization.DateTimeFormat("yyyy-MM-ddTHH:mm:ss.fffZ"); DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T), settings); using (Stream stream = GenerateStreamFromString(jsonString)) { var obj = (T)serializer.ReadObject(stream); output = (T)obj; } return(output); }
/// <summary> /// Serializes an object to Json, compresses it and converts the compressed bytes into Base64 encoding. /// </summary> /// <remarks> /// The function uses <see cref="GZipStream"/> to do the compression. /// </remarks> /// <typeparam name="T">The type of object to serialize</typeparam> /// <param name="obj">The object to serialize.</param> /// <returns>A Base64 string containing the compressed data.</returns> public static string ToJsonCompressed <T> (this T obj) { var settings = new DataContractJsonSerializerSettings { UseSimpleDictionaryFormat = true }; var serializer = new DataContractJsonSerializer(typeof(T), settings); using (var destinationStream = new MemoryStream()) { using (var compressor = new GZipStream(destinationStream, CompressionLevel.Fastest, true)) { serializer.WriteObject(compressor, obj); } return(Convert.ToBase64String(destinationStream.ToArray())); } }
public static void LoadLanguageFile(string path) { var bytes = System.IO.File.ReadAllBytes(path); var settings = new DataContractJsonSerializerSettings(); settings.UseSimpleDictionaryFormat = true; var serializer = new DataContractJsonSerializer(typeof(Data), settings); using (var ms = new MemoryStream(bytes)) { var data = (Data)serializer.ReadObject(ms); foreach (var x in data.kv) { keyToStrings = data.kv; } } }
public static object JsonDeserialize(byte[] jsonBytes, Type objectType, Type[] extraTypes, string rootName) { DataContractJsonSerializerSettings settings = new DataContractJsonSerializerSettings(); settings.KnownTypes = extraTypes; settings.RootName = rootName; DataContractJsonSerializer serializer = new DataContractJsonSerializer(objectType, settings); object returnObject; using (MemoryStream stream = new MemoryStream(jsonBytes)) { returnObject = serializer.ReadObject(stream); } return(returnObject); }
public bool loadValues() { bool loadedSuccessful = true; string filename = "json/kibbles.json"; // check if file exists if (!File.Exists(filename)) { if (MessageBox.Show("Kibble-File '" + filename + "' not found. This tool will not work properly without that file.\n\nDo you want to visit the homepage of the tool to redownload it?", "Error", MessageBoxButtons.YesNo, MessageBoxIcon.Error) == DialogResult.Yes) { System.Diagnostics.Process.Start("https://github.com/cadon/ARKStatsExtractor/releases/latest"); } return(false); } _K.version = new Version(0, 0); DataContractJsonSerializerSettings s = new DataContractJsonSerializerSettings(); s.UseSimpleDictionaryFormat = true; DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(Kibbles), s); FileStream file = File.OpenRead(filename); try { _K = (Kibbles)ser.ReadObject(file); } catch (Exception e) { MessageBox.Show("File Couldn't be opened or read.\nErrormessage:\n\n" + e.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); loadedSuccessful = false; } file.Close(); if (loadedSuccessful) { try { _K.version = new Version(_K.ver); } catch { _K.version = new Version(0, 0); } } //saveJSON(); return(loadedSuccessful); }
private string SerializeOnlineMeeting(OnlineMeetingInformation onlineMeeting) { using (MemoryStream ms = new MemoryStream()) { DataContractJsonSerializerSettings settings = new DataContractJsonSerializerSettings() { UseSimpleDictionaryFormat = true }; DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(OnlineMeetingInformation), settings); ser.WriteObject(ms, onlineMeeting); using (StreamReader sr = new StreamReader(ms)) { ms.Position = 0; return(sr.ReadToEnd()); } } }
public string Serialize <T>(T value) where T : class { var settings = new DataContractJsonSerializerSettings { EmitTypeInformation = EmitTypeInformation.AsNeeded, UseSimpleDictionaryFormat = true }; var serializer = new DataContractJsonSerializer(typeof(T), settings); string output; using (var stream = new MemoryStream()) { serializer.WriteObject(stream, value); output = Encoding.UTF8.GetString(stream.ToArray()); } return(output); }
/// <summary> /// Deserialize a JSON byte array to the supplied generic type. /// </summary> /// <typeparam name="T">Type to convert to</typeparam> /// <param name="jsonBytes">byte[] of the JSON string</param> /// <returns>Object of type T from JSON</returns> public static T Deserialize <T>(byte[] jsonBytes) { try { DataContractJsonSerializerSettings settings = new DataContractJsonSerializerSettings(); settings.DateTimeFormat = new DateTimeFormat("yyyy-MM-ddTHH:mm:ss.fffZ"); DataContractJsonSerializer s = new DataContractJsonSerializer(typeof(T), settings); return((T)s.ReadObject(new MemoryStream(jsonBytes))); } // MSDN did not specify specific exceptions. catch (Exception ex) { // Something generic happened // TODO: Log or the like... throw ex; } }
public TEntity Deserialize <TEntity>( string entity, string datetimeFormat = null) { var settings = new DataContractJsonSerializerSettings(); if (datetimeFormat != null) { settings.DateTimeFormat = new DateTimeFormat(datetimeFormat); } var serializer = new DataContractJsonSerializer( typeof(TEntity), settings); using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(entity))) { return((TEntity)serializer.ReadObject(stream)); } }
static DataContractJsonSerializer GetJsonSerializer(Type type) { lock (JsonSerializersLock) { if (JsonSerializers == null) { JsonSerializers = new Dictionary <Type, DataContractJsonSerializer>(); } if (!JsonSerializers.ContainsKey(type)) { // Simple dictionary format looks like this: { "Key1": "Value1", "Key2": "Value2" } var settings = new DataContractJsonSerializerSettings(); settings.UseSimpleDictionaryFormat = true; var serializer = new DataContractJsonSerializer(type, settings); JsonSerializers.Add(type, serializer); } } return(JsonSerializers[type]); }
public static Dictionary <string, dynamic> Parse(this string value) { if (string.IsNullOrEmpty(value)) { return(null); } var settings = new DataContractJsonSerializerSettings() { UseSimpleDictionaryFormat = true }; var serializer = new DataContractJsonSerializer(typeof(Dictionary <string, dynamic>), settings); using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(value))) { return(serializer.ReadObject(stream) as Dictionary <string, dynamic>); } }
/// <summary> /// Deserialize a json string as Object /// </summary> /// <typeparam name="T">Objecttype</typeparam> /// <param name="json">Jsonstring</param> /// <returns></returns> public static T Deserialize <T>(string json) { try { using (var ms = new MemoryStream(Encoding.UTF8.GetBytes(json))) { var settings = new DataContractJsonSerializerSettings { UseSimpleDictionaryFormat = true }; var serializer = new DataContractJsonSerializer(typeof(T), settings); return((T)serializer.ReadObject(ms)); } } catch (Exception ex) { Exceptions.NewException(ex); return((T)Activator.CreateInstance(typeof(T))); } }
public static string SerializeJSon <T>(T t, string dateTimeFormat = "yyyy-MM-ddTHH:mm:ss") { DataContractJsonSerializerSettings settings = new DataContractJsonSerializerSettings() { DateTimeFormat = new DateTimeFormat(dateTimeFormat), UseSimpleDictionaryFormat = true }; MemoryStream stream = new MemoryStream(); DataContractJsonSerializer ds = new DataContractJsonSerializer(t.GetType(), settings); ds.WriteObject(stream, t); byte[] data = stream.ToArray(); string jsonString = Encoding.UTF8.GetString(data, 0, data.Length); stream.Dispose(); return(jsonString); }
/// <summary> /// Serialize the dictionary object to json string /// </summary> /// <param name="obj">Dictionary object to serialize</param> /// <returns>Json string</returns> public static string Serialize(Dictionary <string, string> obj) { if (obj == null) { return(null); } var settings = new DataContractJsonSerializerSettings() { UseSimpleDictionaryFormat = true }; var serializer = new DataContractJsonSerializer(typeof(Dictionary <string, string>), settings); using (var mem = new MemoryStream()) { serializer.WriteObject(mem, obj); return(Encoding.UTF8.GetString(mem.ToArray())); } }
static public T deserializeJSON <T>(string json) where T : class { MemoryStream ms; DataContractJsonSerializer ser; T var; var settings = new DataContractJsonSerializerSettings { DateTimeFormat = new System.Runtime.Serialization.DateTimeFormat("yyyy-MM-ddTHH:mm:ssK"), }; using (ms = new MemoryStream(Encoding.UTF8.GetBytes(json))) { ser = new DataContractJsonSerializer(typeof(T), settings); var = ser.ReadObject(ms) as T; } return(var); }
// 書き込み public Dictionary <string, object> save() { List <Type> knownTypes = new List <Type> { typeof(List <string>), typeof(List <List <float[]> >) }; DataContractJsonSerializerSettings settings = new DataContractJsonSerializerSettings { UseSimpleDictionaryFormat = false, KnownTypes = knownTypes }; using (FileStream fs = new FileStream(this.fileName, FileMode.Create, FileAccess.Write)){ // インデントをあける using (var writer = JsonReaderWriterFactory.CreateJsonWriter(fs, Encoding.UTF8, true, false)) { var serializer = new DataContractJsonSerializer(typeof(Dictionary <string, object>), settings); serializer.WriteObject(writer, this.fileInfoObject); } } return(this.fileInfoObject); }
IEnumerator Post(string postdata) { UnityWebRequest request = new UnityWebRequest(URL, "POST"); byte[] bodyRaw = Encoding.UTF8.GetBytes(postdata); request.uploadHandler = (UploadHandler) new UploadHandlerRaw(bodyRaw); request.downloadHandler = (DownloadHandler) new DownloadHandlerBuffer(); request.SetRequestHeader("Content-Type", "application/json"); yield return(request.Send()); DataContractJsonSerializerSettings settings = new DataContractJsonSerializerSettings(); settings.MaxItemsInObjectGraph = 10; string json = request.downloadHandler.text; GameObject Messageobj = GameObject.Find("Message"); if (request.responseCode == 200) { GachaResponse data = JsonUtils.ToObject <GachaResponse>(json); //Dbg.s(Messageobj); Text Messagetext = Messageobj.GetComponent <Text>(); Messagetext.text = data.name + "をゲットしました"; GameObject gachacontrollerobj = GameObject.Find("GachaController"); GachaController gachacontroller = gachacontrollerobj.GetComponent <GachaController>(); gachacontroller.Executionflag = true; } else // todo 配列で返ってきたパターンでちゃんと表示できるようにする { ErrorResponse errorobj = JsonUtils.ToObject <ErrorResponse>(json); //errorobj.message = "test"; Text Messagetext = Messageobj.GetComponent <Text>(); Messagetext.text = errorobj.ErrorMessage; Debug.Log("GACHAFAILED"); } }
private void storeDigitalPattern(string dataStoreFilePath, MOTMasterSequence sequence) { Hashtable digitalChannelsHash = DAQ.Environment.Environs.Hardware.DigitalOutputChannels; Dictionary <string, int> digitalChannels = new Dictionary <string, int>(); foreach (DictionaryEntry pair in digitalChannelsHash) { string patternGeneratorBoard = (string)DAQ.Environment.Environs.Hardware.GetInfo("PatternGeneratorBoard"); if (((DigitalOutputChannel)pair.Value).Device == patternGeneratorBoard) { digitalChannels.Add((string)pair.Key, ((DigitalOutputChannel)pair.Value).BitNumber); } } var settings = new DataContractJsonSerializerSettings(); settings.UseSimpleDictionaryFormat = true; // Make format of json file {key : value} instead of {"Key": key, "Value": value} DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(Dictionary <string, int>), settings); string digitalPatternString = sequence.DigitalPattern.Layout.ToString(); TextWriter output = File.CreateText(dataStoreFilePath); output.Write("{"); output.Write("\"channels\":"); using (MemoryStream ms = new MemoryStream()) { serializer.WriteObject(ms, digitalChannels); output.Write(Encoding.Default.GetString(ms.ToArray())); } output.Write(","); output.Write("\"pattern\":"); output.Write("\""); output.Write(System.Web.HttpUtility.JavaScriptStringEncode(digitalPatternString)); output.Write("\""); output.Write("}"); output.Close(); }
public static Hotel Load(string fileName) { Hotel res; using (var fs = new FileStream(fileName, FileMode.Open)) { //var writer = JsonReaderWriterFactory.CreateJsonWriter(fs, Encoding.UTF8, true, true); //var reader = JsonReaderWriterFactory.CreateJsonReader(fs,) var settings = new DataContractJsonSerializerSettings { DateTimeFormat = new DateTimeFormat("MM/dd/yyyy") }; var serializer = new DataContractJsonSerializer(typeof(Hotel), settings); res = (Hotel)serializer.ReadObject(fs); } var a = res.Rooms; return(res); }
public List <ProductionHistoryDto> GetInfo(string urlApi) { var listaProductionHistoryDto = new List <ProductionHistoryDto>(); var client = new HttpClient(); Task <HttpResponseMessage> response = client.GetAsync(urlApi); var settings = new DataContractJsonSerializerSettings { DateTimeFormat = new System.Runtime.Serialization.DateTimeFormat("yyyy-MM-dd'T'HH:mm:ss") }; if (response.Result.IsSuccessStatusCode) { var body = response.Result.Content.ReadAsStreamAsync().Result; var serializado = new DataContractJsonSerializer(typeof(List <ProductionHistoryDto>), settings); listaProductionHistoryDto = (List <ProductionHistoryDto>)serializado.ReadObject(body); } return(listaProductionHistoryDto); }
public DataContractJsonSerializer(Type type, DataContractJsonSerializerSettings settings);