private static async Task <string> GenerateMasterFile(string filePath, object master, AesCryptoKey dataCryptoKey, bool lz4Compression) { var options = StandardResolverAllowPrivate.Options.WithResolver(UnityContractResolver.Instance); if (lz4Compression) { options = options.WithCompression(MessagePackCompression.Lz4BlockArray); } // 変換. var json = master.ToJson(); var bytes = MessagePackSerializer.ConvertFromJson(json, options); // 暗号化. if (dataCryptoKey != null) { bytes = bytes.Encrypt(dataCryptoKey); } // ファイル出力. CreateFileDirectory(filePath); using (var file = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.ReadWrite)) { await file.WriteAsync(bytes, 0, bytes.Length); } var fileHash = json.GetHash(); return(fileHash); }
public static Dictionary <object, object> GetJsonDictionary(string jsonString) { var ms = new MemoryStream(MessagePackSerializer.ConvertFromJson(jsonString)); var resultDictionary = MessagePackSerializer.Typeless.Deserialize(ms, MessagePackSerializerOptions.Standard) as Dictionary <object, object>; return(resultDictionary); }
private string JsonConvert(string json, MessagePackSerializerOptions options) { var sequence = new Sequence <byte>(); var sequenceWriter = new MessagePackWriter(sequence); MessagePackSerializer.ConvertFromJson(json, ref sequenceWriter, options); sequenceWriter.Flush(); return(MessagePackSerializer.ConvertToJson(sequence.AsReadOnlySequence, options)); }
string JsonConvert(string json, MessagePackSerializer serializer) { var sequence = new Sequence <byte>(); var sequenceWriter = new MessagePackWriter(sequence); serializer.ConvertFromJson(json, ref sequenceWriter); sequenceWriter.Flush(); return(serializer.ConvertToJson(sequence.AsReadOnlySequence)); }
public override IEnchantmentValue Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { if (reader.TokenType != JsonTokenType.StartObject) { throw new JsonException(); } reader.Read(); if (reader.TokenType != JsonTokenType.PropertyName) { throw new JsonException(); } if (reader.GetString() != "Type") { throw new JsonException(); } reader.Read(); if (reader.TokenType != JsonTokenType.String) { throw new JsonException(); } var typeName = reader.GetString(); reader.Read(); if (reader.TokenType != JsonTokenType.PropertyName) { throw new JsonException(); } if (reader.GetString() != "Properties") { throw new JsonException(); } reader.Read(); if (reader.TokenType != JsonTokenType.StartObject) { throw new JsonException(); } var rawText = JsonDocument.ParseValue(ref reader).RootElement.GetRawText(); var obj = MessagePackSerializer.Deserialize( AssemblyHandler.FindTypeByName(typeName), MessagePackSerializer.ConvertFromJson(rawText, MessagePackOptions), MessagePackOptions ); while (reader.Read()) { if (reader.TokenType == JsonTokenType.EndObject) { return(obj as IEnchantmentValue); } } throw new JsonException(); }
public object DeserializeFromJson(string data, Type type, CancellationToken cancellationToken = default) { if (cancellationToken.IsCancellationRequested) { _logger.LogInformation($"{nameof(MessagePackCommandDeserializer)}.{nameof(Deserialize)} was cancelled before execution"); cancellationToken.ThrowIfCancellationRequested(); } return(Deserialize(MessagePackSerializer.ConvertFromJson(data, _options, cancellationToken: cancellationToken), type, cancellationToken: cancellationToken)); }
public T DeserializeObject <T>(string json) { if (json == null) { throw new ArgumentNullException(nameof(json)); } var a = MessagePackSerializer.ConvertFromJson(json, MessagePack.Resolvers.ContractlessStandardResolver.Options); return(MessagePackSerializer.Deserialize <T>(a, MessagePack.Resolvers.ContractlessStandardResolver.Options)); }
public T DeserializeFromJson <T>(string data, CancellationToken cancellationToken = default) { if (cancellationToken.IsCancellationRequested) { _logger.LogInformation($"{nameof(MessagePackQueryDeserializer)}.{nameof(Deserialize)} was cancelled before execution"); cancellationToken.ThrowIfCancellationRequested(); } return(Deserialize <T>(MessagePackSerializer.ConvertFromJson(data, _options, cancellationToken: cancellationToken), cancellationToken: cancellationToken)); }
public static CadData?LoadJson(string fname) { StreamReader reader = new StreamReader(fname); reader.ReadLine(); // skip "{\n" string header = reader.ReadLine(); Regex headerPtn = new Regex(@"version=([0-9a-fA-F]+)"); Match m = headerPtn.Match(header); string version = ""; if (m.Groups.Count >= 1) { version = m.Groups[1].Value; } string js = reader.ReadToEnd(); reader.Close(); js = js.Trim(); js = js.Substring(0, js.Length - 1); js = "{" + js + "}"; byte[] bin = MessagePackSerializer.ConvertFromJson(js); if (version == "1001") { MpCadData_v1001 mpcd = MessagePackSerializer.Deserialize <MpCadData_v1001>(bin); CadData cd = new CadData( mpcd.GetDB(), mpcd.ViewInfo.WorldScale, mpcd.ViewInfo.PaperSettings.GetPaperPageSize() ); return(cd); } else if (version == "1002") { MpCadData_v1002 mpcd = MessagePackSerializer.Deserialize <MpCadData_v1002>(bin); CadData cd = new CadData( mpcd.GetDB(), mpcd.ViewInfo.WorldScale, mpcd.ViewInfo.PaperSettings.GetPaperPageSize() ); return(cd); } return(null); }
public void Serialize(ref MessagePackWriter writer, string value, MessagePackSerializerOptions options) { using var sr = new StringReader(value); // Skip first broken byte if (value[0] == '\x01') { sr.Read(_tmp, 0, 1); } MessagePackSerializer.ConvertFromJson(sr, ref writer); }
internal static byte[] JsonToBytes(string json) { if (GlobalDefaults.ObjectEncodingType == GlobalDefaults.EncodingType.MESSAGE_PACK) { return(MessagePackSerializer.ConvertFromJson(json, GlobalDefaults.SerializerOptions)); } else { return(Encoding.UTF8.GetBytes(json)); } //return MessagePackSerializer.ConvertFromJson(json, GlobalDefaults.Serializer); }
public static byte[] Pack(JToken content) { var aes = Aes.Create(); aes.Key = key; aes.IV = iv; aes.Mode = CipherMode.CBC; aes.Padding = PaddingMode.PKCS7; var decrypted = content == null?Array.Empty <byte>() : MessagePackSerializer.ConvertFromJson(content.ToString()); return(aes.CreateEncryptor().TransformFinalBlock(decrypted, 0, decrypted.Length)); }
/// <summary> /// Converts JSON to MessagePack /// </summary> /// <param name="json"></param> /// <param name="privateMembers">Convert private members</param> /// <returns></returns> /// <exception cref="DataConversionException"></exception> public static byte[] JsonToMsgPack(this string json, bool privateMembers = false) { try { return(MessagePackSerializer.ConvertFromJson(json, privateMembers ? ContractlessStandardResolverAllowPrivate.Options : ContractlessStandardResolver.Options)); } catch (MessagePackSerializationException) { throw new DataConversionException("Could not convert JSON to msgpack. Was it valid JSON?"); } }
//Only gets pressed if you're entering the response of a peer you've added. public void OnSubmitButton() { if (SelectedItem == null) { return; } var packet = MessagePackSerializer.ConvertFromJson(InputField.Text); var offer = MessagePackSerializer.Deserialize <SignaledPeer.Offer>(packet); SelectedItem.peer.SetRemoteDescription(offer.type, offer.sdp); foreach (SignaledPeer.BufferedCandidate c in offer.ICECandidates) { SelectedItem.peer.BufferIceCandidate(c); } }
public Dictionary <string, UnitInfo> Load() { var dataFolderPath = Path.Combine(Application.dataPath, "Data", "Units"); var files = Directory.GetFiles(dataFolderPath, "*.json"); var units = new Dictionary <string, UnitInfo>(); foreach (var file in files) { var text = File.ReadAllText(file); var bytes = MessagePackSerializer.ConvertFromJson(text); var unit = MessagePackSerializer.Deserialize <UnitInfo>(bytes); units[unit.Name] = unit; } return(units); }
/// <summary> /// 序列化json字符串为Byte[] /// </summary> /// <param name="jsonStr"></param> /// <returns></returns> public byte[] SerializesJsonString(string jsonStr) { if (jsonStr == null) { return(default(byte[])); } try { return(MessagePackSerializer.ConvertFromJson(jsonStr)); } catch (Exception e) { _logger.LogError($"序列化对象失败:{e.Message}"); } return(default(byte[])); }
public void TestIfFloatCanBeSerializedJson() { // Arrange var value = 0.1f; // Act var json = serializer.SerializeToJson(value); var sequence = new Sequence <byte>(); var sequenceWriter = new MessagePackWriter(sequence); serializer.ConvertFromJson(json, ref sequenceWriter); sequenceWriter.Flush(); var deserialized = serializer.Deserialize <float>(sequence.AsReadOnlySequence); // Assert Assert.Equal(value, deserialized); }
public async Task <IEnumerable <CandleStick> > GetCandleSticksAsync(GetCandleStickOptions candleStickOptions) { Throw.IfNullOrWhiteSpace(candleStickOptions.Symbol); Throw.IfNull(candleStickOptions.Interval, nameof(candleStickOptions.Interval)); string path = "klines"; if (candleStickOptions.Limit < 0) { throw new ArgumentOutOfRangeException(nameof(candleStickOptions.Limit)); } if (candleStickOptions.Limit > 1000) { candleStickOptions.Limit = 1000; } path += candleStickOptions.ToString(); HttpResponse result = await this.http.GetAsync(this.baseUrl + path); byte[] bytes = MessagePackSerializer.ConvertFromJson(result.Response); return(MessagePackSerializer.Deserialize <CandleStick[]>(bytes)); }
public void Test_MessagePack() { var mc = new MyClass { Age = 99, FirstName = "hoge", LastName = "hoge", }; var res = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(mc)); // Call Serialize/Deserialize, that's all. byte[] bytes = MessagePackSerializer.Serialize(mc); MyClass mc2 = MessagePackSerializer.Deserialize <MyClass>(bytes); // You can dump MessagePack binary blobs to human readable json. // Using indexed keys (as opposed to string keys) will serialize to MessagePack arrays, // hence property names are not available. // [99,"hoge","huga"] var json = MessagePackSerializer.ConvertToJson(bytes); var res2 = MessagePackSerializer.ConvertFromJson(json); MyClass mc3 = MessagePackSerializer.Deserialize <MyClass>(bytes); Console.WriteLine(json); }
public static T MpToObj <T>(this string obj) { return(MessagePackSerializer.Deserialize <T>(MessagePackSerializer.ConvertFromJson(obj)));; }
//// POST: api/Convert public JsonResult <ConvertResult> Post() { string data = Request.Content.ReadAsStringAsync().Result; var client = new HttpClient(); byte[] byteArray = MessagePackSerializer.ConvertFromJson($"{{ \"fileId\": \"{JObject.Parse(data)["fileId"]}\"}}"); HttpContent httpContent = new ByteArrayContent(byteArray); client.DefaultRequestHeaders.Add("Authorization", Request.Headers.GetValues("Authorization")); //Crypto.Decrypt(Properties.Settings.Default.UserData, "pass")); var res = client.PostAsync("https://adm.ijro.uz/api/files.download", httpContent).Result; var arr = res.Content.ReadAsByteArrayAsync().Result; var json = MessagePackSerializer.ConvertToJson(arr); var file = JsonConvert.DeserializeObject <ReportAPI.Models.IjroFile>(json); file.Name = Path.GetFileNameWithoutExtension(file.Name) + ".pdf"; var fileBytes = Convert.FromBase64String(file.Content); using (RichEditDocumentServer wordProcessor = new RichEditDocumentServer()) { try { string path = HttpContext.Current.Server.MapPath("~/Files/"); wordProcessor.Options.Import.OpenXml.IgnoreDeletedText = false; wordProcessor.Options.Import.OpenXml.IgnoreInsertedText = false; wordProcessor.LoadDocument(fileBytes, DocumentFormat.OpenXml); Document document = wordProcessor.Document; foreach (var field in document.Fields) { string fieldCode = document.GetText(field.CodeRange).Trim(); if (fieldCode.ToUpper().StartsWith("TOC")) { field.Locked = true; ReadOnlyHyperlinkCollection tocLinks = document.Hyperlinks.Get(field.ResultRange); foreach (Hyperlink tocLink in tocLinks) { CharacterProperties cp = document.BeginUpdateCharacters(tocLink.Range); cp.Style = document.CharacterStyles["Default Paragraph Font"]; document.EndUpdateCharacters(cp); } } } document.Fields.Update(); foreach (Field field in document.Fields) { string fieldCode = document.GetText(field.CodeRange).Trim(); if (fieldCode.ToUpper().StartsWith("TOC")) { CharacterProperties cp = document.BeginUpdateCharacters(field.ResultRange); cp.Style = document.CharacterStyles["Default Paragraph Font"]; document.EndUpdateCharacters(cp); } } using (var ms = new MemoryStream()) { wordProcessor.ExportToPdf(ms); using (var fs = File.Open(path + "/" + file.Name, FileMode.OpenOrCreate)) { ms.Position = 0; ms.CopyTo(fs); } return(Json(new ConvertResult() { FileUrl = string.Format(@"http://{0}/api/GetFile?fileName={1}", "192.168.70.141:8080", Uri.EscapeDataString(file.Name)) })); } } catch (Exception ex) { return(Json(new ConvertResult() { FileUrl = ex.Message })); // Your code to handle cancellation } } }
public static void UpdateAPI() { string rawAPIFile = global.ProSwapperFolder + "api.ProSwapper"; string rawGlobalFile = global.ProSwapperFolder + "global.ProSwapper"; GlobalAPI.Root globalapi = null; #if DEBUG apidata = JsonConvert.DeserializeObject <APIRoot>(File.ReadAllText("api.json")); apidata.timestamp = global.GetEpochTime(); globalapi = JsonConvert.DeserializeObject <GlobalAPI.Root>(File.ReadAllText("global.json")); string json = JsonConvert.SerializeObject(apidata, Formatting.None, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore//Makes filesize smaller hehe }); byte[] compressedapi = MessagePackSerializer.ConvertFromJson(json, MessagePackSerializerOptions.Standard); File.WriteAllBytes($"{global.version}.json", ByteCompression.Compress(compressedapi)); #else try { download : double TimeNow = global.GetEpochTime(); if (global.CurrentConfig.LastOpenedAPI + 3600 < TimeNow) { //Get api coz it wasnt fetched more than an hour ago using (WebClient web = new WebClient()) { //Download api & global byte[] rawAPI = web.DownloadData($"{ProSwapperEndpoint}/{global.version}.json"); string rawGlobal = web.DownloadString($"{ProSwapperEndpoint}/global.json"); //Decompress api & set apidata = JsonConvert.DeserializeObject <APIRoot>(MessagePackSerializer.ConvertToJson(ByteCompression.Decompress(rawAPI))); globalapi = JsonConvert.DeserializeObject <GlobalAPI.Root>(rawGlobal); File.WriteAllBytes(rawAPIFile, rawAPI); File.WriteAllText(rawGlobalFile, rawGlobal); } global.CurrentConfig.LastOpenedAPI = TimeNow; } else { if (!File.Exists(rawAPIFile) || !File.Exists(rawGlobalFile)) { global.CurrentConfig.LastOpenedAPI = 0; goto download; } //Was fetched within the hour //Download api & global byte[] rawAPI = File.ReadAllBytes(rawAPIFile); string rawGlobal = File.ReadAllText(rawGlobalFile); //Decompress api & set apidata = JsonConvert.DeserializeObject <APIRoot>(MessagePackSerializer.ConvertToJson(ByteCompression.Decompress(rawAPI))); globalapi = JsonConvert.DeserializeObject <GlobalAPI.Root>(rawGlobal); } } catch (Exception ex) { Program.logger.LogError(ex.Message); Main.ThrowError($"Pro Swapper needs an Internet connection to run, if you are already connected to the Internet Pro Swapper's API may be blocked in your country, please use a VPN or try disabling your firewall, if you are already doing this please refer to this error: \n\n{ex.Message}", true); } #endif apidata.discordurl = globalapi.discordurl; apidata.version = globalapi.version; apidata.status[0] = globalapi.status[0]; }
public void LoadScores() { HighScores = new List <HighScoreData>(MessagePackSerializer.Deserialize <HighScoreData[]>(MessagePackSerializer.ConvertFromJson(PlayerPrefs.GetString("HighScores")))); }
public static IMessage DeserializeJson(string json) { byte[] bytes = MessagePackSerializer.ConvertFromJson(json); return(Deserialize(bytes)); }
private void MessagePackSample() { Debug.Log("#Basic and ConvertToJson/ConvertFromJson, SerializeToJson samples."); { var target = new PersonBasic { Id = 0, Addresses = new AddressBasic[] { new AddressBasic { Zipcode = 1002321, Address = "hoge", TelephoneNumber = "0120198198" }, new AddressBasic { Zipcode = 1008492, Address = "fuga", TelephoneNumber = "0120231564" }, }, }; var serialized = MessagePackSerializer.Serialize(target); var json = MessagePackSerializer.ConvertToJson(serialized); Debug.Log(json); var serializedFromJson = MessagePackSerializer.ConvertFromJson(json); var deserialized = MessagePackSerializer.Deserialize <PersonBasic>(serializedFromJson); Debug.Log(MessagePackSerializer.SerializeToJson(deserialized)); } Debug.Log("#Attribute for properties sample."); { var target = new AddressSample1 { Zipcode = 100, Address = "hogehoge", TelephoneNumber = "0120999999", }; var serialized = MessagePackSerializer.Serialize(target); Debug.Log(MessagePackSerializer.ConvertToJson(serialized)); var deserialized = MessagePackSerializer.Deserialize <AddressSample1>(serialized); Debug.Log(MessagePackSerializer.SerializeToJson(deserialized)); } Debug.Log("#Non-Attribute at property sample."); { var target = new AddressSample2 { Zipcode = 200, Address = "hogehoge" }; var serialized = MessagePackSerializer.Serialize(target); Debug.Log(MessagePackSerializer.ConvertToJson(serialized)); var deserialized = MessagePackSerializer.Deserialize <AddressSample2>(serialized); Debug.Log(MessagePackSerializer.SerializeToJson(deserialized)); } Debug.Log("#Plane class like Json.NET."); { #if WINDOWS_UWP Debug.Log("dose'nt work in IL2CPP"); #else var target = new AddressSample3 { Zipcode = 300, Address = "hogehoge" }; // MessagePack.Resolvers.DynamicObjectResolverAllowPrivate.Optionsを使うとプライベートメンバーにも対応 var serialized = MessagePackSerializer.Serialize(target, MessagePack.Resolvers.ContractlessStandardResolver.Options); Debug.Log(MessagePackSerializer.ConvertToJson(serialized)); var deserialized = MessagePackSerializer.Deserialize <AddressSample3>(serialized, MessagePack.Resolvers.ContractlessStandardResolver.Options); Debug.Log(MessagePackSerializer.SerializeToJson(deserialized, MessagePack.Resolvers.ContractlessStandardResolver.Options)); #endif } Debug.Log("#Using interface sample."); { IUnionSample target = new FooClass { Zipcode = 400 }; var serialized = MessagePackSerializer.Serialize(target); Debug.Log(MessagePackSerializer.ConvertToJson(serialized)); var deserialized = MessagePackSerializer.Deserialize <IUnionSample>(serialized); // C# 7が使えない場合は、as か インターフェイスに識別子を持たせるなど switch (deserialized) { case FooClass x: Debug.Log(x.Zipcode); break; case BarClass x: Debug.Log(x.Address); break; default: break; } } Debug.Log("#Using stream sample."); { var target = new AddressSample1 { Zipcode = 500, Address = "hoge" }; using (var stream = new MemoryStream()) { MessagePackSerializer.SerializeAsync(stream, target).Wait(); var serialized = stream.ToArray(); var deserialized = MessagePackSerializer.Deserialize <AddressSample1>(serialized); Debug.Log(MessagePackSerializer.ConvertToJson(serialized)); stream.Position = 0; var deserializedFromStream = MessagePackSerializer.DeserializeAsync <AddressSample1>(stream).Result; Debug.Log(MessagePackSerializer.SerializeToJson(deserializedFromStream)); } var target2 = new AddressSample2 { Zipcode = 600, Address = "fuga", }; using (var stream = new MemoryStream()) { MessagePackSerializer.SerializeAsync(stream, target).Wait(); MessagePackSerializer.SerializeAsync(stream, target2).Wait(); Debug.Log(MessagePackSerializer.ConvertToJson(stream.ToArray())); stream.Position = 0; var deserializedFromStream1 = MessagePackSerializer.DeserializeAsync <AddressSample1>(stream).Result; Debug.Log(MessagePackSerializer.SerializeToJson(deserializedFromStream1)); var deserializedFromStream2 = MessagePackSerializer.DeserializeAsync <AddressSample2>(stream).Result; Debug.Log(MessagePackSerializer.SerializeToJson(deserializedFromStream2)); } } }
public static T DeserializeJson <T>(string json) { byte[] bytes = MessagePackSerializer.ConvertFromJson(json, Options); return(MessagePackSerializer.Deserialize <T>(bytes, Options)); }
public virtual void FromJson(string json) { var data = MessagePackSerializer.ConvertFromJson(json); this.UnPack(data); }
bool IsSongUsable(string path, out AvailableSongData availableSong) { availableSong = new AvailableSongData(); string infoFilePath = path + "\\info.dat"; if (File.Exists(infoFilePath)) { SongInfoFileData infoFileData = MessagePackSerializer.Deserialize <SongInfoFileData>(MessagePackSerializer.ConvertFromJson(File.ReadAllText(infoFilePath))); availableSong.DirectoryPath = path; availableSong.SongInfoFileData = infoFileData; return(true); } return(false); }
public void OnJoinMeshButton() { var packet = MessagePackSerializer.ConvertFromJson(InputField.Text); networking.JoinMesh(packet); }
/* * public override T Deserialize<T>(MessageEventArgs args) * { * var bytes = MessagePackSerializer.FromJson(args.Data); * return CoflnetEncoder.Instance.Deserialize<T>(bytes); * } * * * public override ServerCommandData Deserialize(MessageEventArgs args) * { * var bytes = MessagePackSerializer.FromJson(args.Data); * return (ServerCommandData)CoflnetEncoder.Instance.Deserialize<DevCommandData>(bytes); * } */ public override T Deserialize <T>(byte[] args) { var bytes = MessagePackSerializer.ConvertFromJson(Encoding.UTF8.GetString(args)); return(CoflnetEncoder.Instance.Deserialize <T>(bytes)); }