public void CannotCreateIfNoneConstructorsMatch() { ObjectConstructor ctor = new ObjectConstructor(typeof(Point)); ImportContext context = JsonConvert.CreateImportContext(); ctor.CreateObject(context, JsonText.CreateReader("{ z: x: 123 }")); }
private string GetTag() { string text1 = JsonText.transfer(line1.GetJsonText()); string text2 = JsonText.transfer(line2.GetJsonText()); string text3 = JsonText.transfer(line3.GetJsonText()); string text4 = JsonText.transfer(line4.GetJsonText()); if (Cmd1.Text != "") { text1 = text1.Substring(0, text1.Length - 1) + ",\\\"clickEvent\\\":{\\\"action\\\":\\\"run_command\\\",\\\"value\\\":\\\"" + Cmd1.Text + "\\\"}}"; } if (Cmd2.Text != "") { text2 = text2.Substring(0, text2.Length - 1) + ",\\\"clickEvent\\\":{\\\"action\\\":\\\"run_command\\\",\\\"value\\\":\\\"" + Cmd2.Text + "\\\"}}"; } if (Cmd3.Text != "") { text3 = text3.Substring(0, text3.Length - 1) + ",\\\"clickEvent\\\":{\\\"action\\\":\\\"run_command\\\",\\\"value\\\":\\\"" + Cmd3.Text + "\\\"}}"; } if (Cmd4.Text != "") { text4 = text4.Substring(0, text4.Length - 1) + ",\\\"clickEvent\\\":{\\\"action\\\":\\\"run_command\\\",\\\"value\\\":\\\"" + Cmd4.Text + "\\\"}}"; } if (give.IsChecked == true || item.IsChecked == true) { return("{BlockEntityTag:{Text1:\"" + text1 + "\",Text2:\"" + text2 + "\",Text3:\"" + text3 + "\",Text4:\"" + text4 + "\"}}"); } else { return("{Text1:\"" + text1 + "\",Text2:\"" + text2 + "\",Text3:\"" + text3 + "\",Text4:\"" + text4 + "\"}"); } }
public void Export() { var context = JsonConvert.CreateImportContext(); var importer = new ExpandoObjectImporter(); var expando = importer.Import(context, JsonText.CreateReader(@" { num: 123, flag: true, str: foobar, nil: null, obj: { x: 456, y: 789 }, arr: [ 123, { x: 456, y: 789 } ], }")); Assert.IsNotNull(expando); Assert.IsInstanceOf <ExpandoObject>(expando); dynamic obj = expando; Assert.AreEqual(123, ((JsonNumber)obj.num).ToInt32()); Assert.IsTrue((bool)obj.flag); Assert.AreEqual("foobar", (string)obj.str); Assert.IsInstanceOf <ExpandoObject>((object)obj.obj); Assert.AreEqual(456, ((JsonNumber)obj.obj.x).ToInt32()); Assert.AreEqual(789, ((JsonNumber)obj.obj.y).ToInt32()); Assert.IsInstanceOf <IList <object> >((object)obj.arr); var arr = (IList <object>)obj.arr; Assert.AreEqual(123, ((JsonNumber)arr[0]).ToInt32()); Assert.IsInstanceOf <ExpandoObject>(arr[1]); Assert.AreEqual(456, ((JsonNumber)(((dynamic)(arr[1])).x)).ToInt32()); Assert.AreEqual(789, ((JsonNumber)(((dynamic)(arr[1])).y)).ToInt32()); }
public void ImportTuple1FromNull() { var importer = new ValueTupleImporter(typeof(ValueTuple <int>)); var result = importer.Import(JsonConvert.CreateImportContext(), JsonText.CreateReader("null")); Assert.IsNull(result); }
private static string SwapPersonNames() { var writer = JsonText.CreateWriter(new StringBuilder()); writer.WriteStartObject(); writer.WriteMember("id"); writer.WriteString("12345"); writer.WriteMember("method"); writer.WriteString("ru.siqube.itan.swapNames"); writer.WriteMember("params"); writer.WriteStartObject(); writer.WriteMember("p"); writer.WriteStartObject(); writer.WriteMember("firstName"); writer.WriteString("Alex"); writer.WriteMember("lastName"); writer.WriteString("Baranov"); writer.WriteEndObject(); writer.WriteMember("needChange"); writer.WriteBoolean(false); writer.WriteEndObject(); writer.WriteEndObject(); return(writer.ToString()); }
static void Main(string[] args) { string JsonText; try { GetWebApi getWebApi = new GetWebApi("http://api.m.taobao.com/rest/api3.do?api=mtop.common.getTimestamp"); JsonText = getWebApi.GetContent(); } catch (Exception) { Console.WriteLine("Because of network error this software will be shutdown now !"); return; } JsonText = JsonText.Replace("[\"SUCCESS::接口调用成功\"]", "\"OK\""); JsonText = JsonText.Replace(":{\"t\":\"", ":\""); JsonText = JsonText.Replace("}}", "}"); //Console.WriteLine(JsonText); RootObject rootObject = JsonConvert.DeserializeObject <RootObject>(JsonText); long TimeStamp = long.Parse(rootObject.data); ToTime(TimeStamp); }
/************************************************************************/ /* GET */ /************************************************************************/ #if TEST public PipelineDescriptor GetPipeline(string pipelineName) { PipelineDescriptor pipeline = null; ImportContext impctx = new ImportContext(); impctx.Register(new ListImporter <ModuleDescriptor>()); impctx.Register(new ListImporter <EndpointDescriptor>()); impctx.Register(new ListImporter <ConnectionDescriptor>()); switch (pipelineName) { case "root": pipeline = ((Response <PipelineDescriptor>)impctx.Import( typeof(Response <PipelineDescriptor>), JsonText.CreateReader(test_RootPipelineJSON))).GetResponse(); break; case "pipeline1": pipeline = ((Response <PipelineDescriptor>)impctx.Import( typeof(Response <PipelineDescriptor>), JsonText.CreateReader(test_Pipeline1JSON))).GetResponse(); break; } return(pipeline); }
public virtual object Invoke(Type returnType, string method, object args) { if (method == null) { throw new ArgumentNullException("method"); } if (method.Length == 0) { throw new ArgumentException(null, "method"); } if (returnType == null) { throw new ArgumentNullException("returnType"); } WebRequest request = GetWebRequest(new Uri(Url)); request.Method = "POST"; using (Stream stream = request.GetRequestStream()) using (StreamWriter writer = new StreamWriter(stream, Encoding.UTF8)) { JsonObject call = new JsonObject(); call["id"] = ++_id; call["method"] = method; call["params"] = args != null ? args : _zeroArgs; JsonConvert.Export(call, writer); } using (WebResponse response = GetWebResponse(request)) using (Stream stream = response.GetResponseStream()) using (StreamReader reader = new StreamReader(stream, Encoding.UTF8)) return(OnResponse(JsonText.CreateReader(reader), returnType)); }
private Thing CreateThing(string json) { ObjectConstructor ctor = new ObjectConstructor(typeof(Thing)); ImportContext context = JsonConvert.CreateImportContext(); ObjectConstructionResult result = ctor.CreateObject(context, JsonText.CreateReader(json)); return((Thing)result.Object); }
public void Import() { var reader = JsonText.CreateReader("[42,{x:123,y:456},foo,true,null,false]"); var importer = new JsonBufferImporter(); var buffer = (JsonBuffer)importer.Import(JsonConvert.CreateImportContext(), reader); Assert.AreEqual("[42,{\"x\":123,\"y\":456},\"foo\",true,null,false]", buffer.ToString()); }
public static void Export(object value, TextWriter writer) { if (writer == null) { throw new ArgumentNullException("writer"); } Export(value, JsonText.CreateWriter(writer)); }
public void Export() { var sb = new StringBuilder(); var writer = JsonText.CreateWriter(sb); var buffer = JsonBuffer.From("[42,{x:123,y:456},foo,true,null,false]"); var exporter = new JsonBufferExporter(); exporter.Export(JsonConvert.CreateExportContext(), buffer, writer); Assert.AreEqual("[42,{\"x\":123,\"y\":456},\"foo\",true,null,false]", sb.ToString()); }
static void AssertImport(object expected, string input) { var importer = new ValueTupleImporter(expected.GetType()); var reader = JsonText.CreateReader(input); var context = JsonConvert.CreateImportContext(); var actual = importer.Import(context, reader); Assert.IsTrue(reader.EOF, "Reader must be at EOF."); Assert.AreEqual(expected, actual); }
public void NonMemberImport() { var importer = new ComponentImporter(typeof(DynamicThing)); var context = new ImportContext(); const string json = "{ str1: value1, str2: value2, num: 42 }"; var thing = (DynamicThing)importer.Import(context, JsonText.CreateReader(json)); Assert.AreEqual(2, thing.NonMembers.Count); Assert.AreEqual("value1", thing.NonMembers["str1"]); Assert.AreEqual("value2", thing.NonMembers["str2"]); }
public void Construction() { ObjectConstructor ctor = new ObjectConstructor(typeof(Point)); ImportContext context = JsonConvert.CreateImportContext(); const string json = "{ y: 456, x: 123 }"; ObjectConstructionResult result = ctor.CreateObject(context, JsonText.CreateReader(json)); Point point = (Point)result.Object; Assert.AreEqual(123, point.X); Assert.AreEqual(456, point.Y); Assert.AreEqual(0, JsonBuffer.From(result.TailReader).GetMemberCount()); }
public virtual object InvokeArray(Type returnType, string[] method, object[] args) { if (method == null) { throw new ArgumentNullException("method"); } if (method.Length == 0) { throw new ArgumentException(null, "method"); } if (returnType == null) { throw new ArgumentNullException("returnType"); } try { var request = GetWebRequest(new Uri(Url)); request.Method = "POST"; var utf8EmitBom = new UTF8Encoding(false); using (var stream = request.GetRequestStream()) using (var writer = new StreamWriter(stream, utf8EmitBom)) { var calls = new JsonArray(); var i = 0; foreach (var meth in method) { var call = new JsonObject(); call["id"] = ++_id; call["jsonrpc"] = "2.0"; call["method"] = method[i]; if (args[i] != null) { call["params"] = args[i]; } calls.Add(call); i++; } Logger.Instance().Log("RPC", calls.ToString()); JsonConvert.Export(calls, writer); } object ret; using (var response = GetWebResponse(request)) using (var stream = response.GetResponseStream()) using (var reader = new StreamReader(stream, Encoding.UTF8)) ret = OnResponseArray(JsonText.CreateReader(reader), returnType); return(ret); } catch (WebException ex) { throw new JsonException("Invalid JSON-RPC response. It contains neither a result nor error : " + ex.Message); } }
public void ValueTypeWithDefaultConstructorConstruction() { var constructor = new ObjectConstructor(typeof(ValueThing)); var result = constructor.CreateObject(new ImportContext(), JsonText.CreateReader("{foo:bar}")); Assert.IsInstanceOf <ValueThing>(result.Object); var tail = result.TailReader; tail.ReadToken(JsonTokenClass.Object); Assert.AreEqual("foo", tail.ReadMember()); Assert.AreEqual("bar", tail.ReadString()); tail.ReadToken(JsonTokenClass.EndObject); }
public void Export() { var context = JsonConvert.CreateExportContext(); dynamic obj = new ExpandoObject(); obj.num = 123; obj.flag = true; obj.str = "foobar"; obj.nums = new[] { 123, 456, 789 }; var json = new StringBuilder(); new ExpandoObjectExporter().Export(context, obj, JsonText.CreateWriter(json)); Assert.AreEqual("{\"num\":123,\"flag\":true,\"str\":\"foobar\",\"nums\":[123,456,789]}", json.ToString()); }
public void Process(TextReader request, TextWriter response, bool authorised) { if (request == null) { throw new ArgumentNullException("request"); } if (response == null) { throw new ArgumentNullException("response"); } Process(JsonText.CreateReader(request), JsonText.CreateWriter(response), authorised); }
public virtual object Invoke(Type returnType, string method, object args) { if (method == null) { throw new ArgumentNullException("method"); } if (method.Length == 0) { throw new ArgumentException(null, "method"); } if (returnType == null) { throw new ArgumentNullException("returnType"); } try { var request = GetWebRequest(new Uri(Url)); request.Method = "POST"; request.Timeout = 300000; var utf8EmitBom = new UTF8Encoding(false); using (var stream = request.GetRequestStream()) { stream.ReadTimeout = 300000; using (var writer = new StreamWriter(stream, utf8EmitBom)) { var call = new JsonObject(); call["id"] = ++_id; call["jsonrpc"] = "2.0"; call["method"] = method; if (args != null) { call["params"] = args; } JsonConvert.Export(call, writer); } } object ret; using (var response = GetWebResponse(request)) using (var stream = response.GetResponseStream()) using (var reader = new StreamReader(stream, Encoding.UTF8)) ret = OnResponse(JsonText.CreateReader(reader), returnType); return(ret); } catch (WebException ex) { throw new JsonException("Invalid JSON-RPC response. It contains neither a result nor error : " + ex.Message); } }
public void UnicodeText() { // see https://www.dropbox.com/developers/reference/json-encoding string text = "\"some_üñîcødé_and_\x7f\""; JsonText jsonText = JsonText.Parse(text); Assert.AreEqual(@"some_\u00fc\u00f1\u00eec\u00f8d\u00e9_and_\u007f", jsonText.Value); Assert.AreEqual(text.Trim('\"'), jsonText.FromJson <string>()); text = "\"Welcome 🤗 to a link🔗\""; jsonText = JsonText.Parse(text); Assert.AreEqual(@"Welcome \ud83e\udd17 to a link\ud83d\udd17", jsonText.Value); Assert.AreEqual(text.Trim('\"'), jsonText.FromJson <string>()); text = "\"More than\rone line.\nThree in fact!\r\nNo four :-)\""; jsonText = JsonText.Parse(text); Assert.AreEqual(@"More than\u000done line.\u000aThree in fact!\u000d\u000aNo four :-)", jsonText.Value); Assert.AreEqual(text.Trim('\"'), jsonText.FromJson <string>()); }
public void ConstructionWithTail() { ObjectConstructor ctor = new ObjectConstructor(typeof(Point)); ImportContext context = JsonConvert.CreateImportContext(); const string json = "{ y: 456, z: 789, x: 123 }"; ObjectConstructionResult result = ctor.CreateObject(context, JsonText.CreateReader(json)); Point point = (Point)result.Object; Assert.AreEqual(123, point.X); Assert.AreEqual(456, point.Y); NamedJsonBuffer[] tail = JsonBuffer.From(result.TailReader).GetMembersArray(); Assert.AreEqual(1, tail.Length); NamedJsonBuffer z = tail[0]; Assert.AreEqual("z", z.Name); Assert.AreEqual(789, z.Buffer.GetNumber().ToInt32()); }
//! move out of current pipeline public PipelineDescriptor NavigatePop() { ImportContext impctx = new ImportContext(); impctx.Register(new ListImporter <ModuleDescriptor>()); impctx.Register(new ListImporter <ConnectionDescriptor>()); impctx.Register(new ListImporter <EndpointDescriptor>()); PipelineDescriptor newPipeline = ((Response <PipelineDescriptor>)impctx.Import( typeof(Response <PipelineDescriptor>), JsonText.CreateReader(test_RootPipelineJSON))).GetResponse(); NuiState.Instance.level--; currentPipeline = newPipeline; return(newPipeline); }
public void ParseLiteral() { Assert.IsFalse(JsonBool.Parse("false").Value); Assert.IsTrue(JsonBool.Parse("true").Value); Assert.AreEqual("false", new JsonBool(false).ToString()); Assert.AreEqual("true", new JsonBool(true).ToString()); Assert.AreEqual("id", JsonText.Parse("\"id\"").Value); Assert.AreEqual(89, JsonNumber.Parse("89").Byte); Assert.AreEqual("\"{<guid>}\"", JsonText.Parse("\"\\\"{<guid>}\\\"\"").Value); Assert.AreEqual(-0.5m, JsonNumber.Parse("-0.5").Decimal); Assert.AreEqual(500d, JsonNumber.Parse("+0.5E3").Double); Assert.AreEqual(0.0005d, JsonNumber.Parse("0.5E-3").Double); JsonObject o = new JsonObject(("name", new JsonText("Lars \"kodekarl\" Hammer"))); const string json = "{\"name\":\"Lars \\\"kodekarl\\\" Hammer\"}"; Assert.AreEqual(json, o.ToString()); Assert.AreEqual(json, JsonValue.Parse(json).ToString()); Assert.AreEqual(json, JsonValue.Parse(o.Format()).ToString()); }
/// <summary> /// /// </summary> /// <param name="request"></param> /// <exception cref="ArgumentNullException">строка запроса не может быть равна null</exception> /// <exception cref="ArgumentException">json request некорректен по формату</exception> public JsonRequest(string request) { if (request == null) { throw new ArgumentNullException("request"); } if (request.Length == 0) { throw new ArgumentException(null, "request"); } mRequest = request; Args = null; // parse request here var reader = JsonText.CreateReader(mRequest); var members = JsonBuffer.From(reader).GetMembersArray(); foreach (var member in members) { switch (member.Name) { case "id": Id = (long)JsonConvert.Import(typeof(long), member.Buffer.CreateReader()); break; case "method": Method = (string)JsonConvert.Import(typeof(string), member.Buffer.CreateReader()); break; case "params": Args = JsonConvert.Import(typeof(object), member.Buffer.CreateReader()); break; } } if (Method.Length == 0) { throw new ArgumentException("method"); } }
public void TestTexts() { //text Assert.AreEqual("{\"text\":\"hel\\nlo\"}", new JsonText.Text("hel\nlo").GetJsonString(), "Text doesn't return correct string"); Assert.ThrowsException <ArgumentNullException>(() => new JsonText.Text(null !), "Text should throw exception when null"); //translate Assert.AreEqual("{\"translate\":\"hel\\\"lo\",\"with\":[{\"text\":\"insert1\"},{\"text\":\"insert2\"}]}", new JsonText.Translate("hel\"lo", new BaseJsonText[] { new JsonText.Text("insert1"), new JsonText.Text("insert2") }).GetJsonString(), "Translate doesn't return correct string"); Assert.AreEqual("{\"translate\":\"hello\"}", new JsonText.Translate("hello").GetJsonString(), "Translate doesn't return correct string when only translate is specified"); Assert.ThrowsException <ArgumentNullException>(() => new JsonText.Translate(null !), "Translate should throw exception if translate is null"); //names Assert.AreEqual("{\"selector\":\"@a[name=\\\"Name\\\"]\"}", new JsonText.Names(new Selector(ID.Selector.a) { SingleName = "Name" }).GetJsonString(), "Names doesn't return correct string"); Assert.ThrowsException <ArgumentNullException>(() => new JsonText.Names(null !), "Names selector should throw exception if null"); //keybind Assert.AreEqual("{\"keybind\":\"key.inventory\"}", new JsonText.KeyBind(ID.Key.inventory).GetJsonString(), "Keybind doesn't return correct string"); //data Assert.AreEqual("{\"nbt\":\"test.t{a:\\\"hello\\\"}\",\"interpret\":true,\"entity\":\"@s[name=\\\"Name\\\"]\"}", new JsonText.Data(new EntityDataLocation(new Selector(ID.Selector.s) { SingleName = "Name" }, "test.t{a:\"hello\"}"), true).GetJsonString(), "Data entity doesn't return correct string"); Assert.AreEqual("{\"nbt\":\"path\",\"interpret\":false,\"block\":\"~1 ~2 ~3\"}", new JsonText.Data(new BlockDataLocation(new Coords(1, 2, 3), "path"), false).GetJsonString(), "Data block doesn't return correct string"); Assert.AreEqual("{\"nbt\":\"path\",\"interpret\":false,\"storage\":\"space:stor\"}", new JsonText.Data(new StorageDataLocation(new Storage(MockNamespace.GetNamespace("space"), "stor"), "path"), false).GetJsonString(), "Data storage doesn't return correct string"); Assert.ThrowsException <ArgumentNullException>(() => new JsonText.Data(null !, true), "Data should throw exception if location is null"); //score Assert.AreEqual("{\"score\":{\"name\":\"@s[name=\\\"Name\\\"]\",\"objective\":\"test\"}}", new JsonText.Score(new Selector(ID.Selector.s) { SingleName = "Name" }, new Objective("test")).GetJsonString(), "Score doesn't return correct string"); Assert.ThrowsException <ArgumentException>(() => new JsonText.Score(ID.Selector.e, new Objective("something")), "Score should throw exception is selector selects too many things"); _ = new JsonText.Score(AllSelector.GetSelector(), new Objective("something")); Assert.ThrowsException <ArgumentNullException>(() => new JsonText.Score(null !, new Objective("something")), "Score should throw exception if selector is null"); Assert.ThrowsException <ArgumentNullException>(() => new JsonText.Score(ID.Selector.s, null !), "Score should throw exception if objective is null"); }
private static object Import(bool hasValue, string input) { JsonReader reader = JsonText.CreateReader(input); ImportContext context = JsonConvert.CreateImportContext(); ThingImporter thingImporter = new ThingImporter(); context.Register(thingImporter); NullableImporter importer = new NullableImporter(typeof(Thing?)); object thing = importer.Import(context, reader); Assert.AreEqual(hasValue, thingImporter.ImportCalled); if (hasValue) { Assert.IsInstanceOfType(typeof(Thing), thing); } else { Assert.IsNull(thing); } Assert.IsTrue(reader.EOF, "Reader must be at EOF."); return(thing); }
private string GetTag() { string tit = "title:\"自定义Json书\",", aut = "author:\"author\","; if (title.Text != "" && title.Text != null) { tit = "title:\"" + title.Text + "\","; } if (author.Text != "" && author.Text != null) { aut = "author:\"" + author.Text + "\","; } string txt = ""; for (int i = 0; i < pageList.Children.Count - 1; i++) { BookPage p = pageList.Children[i] as BookPage; txt += "\"" + JsonText.transfer(p.doc.GetJsonText()) + "\","; } return("{" + tit + aut + "pages:[" + txt.Substring(0, txt.Length - 1) + "]}"); }
public void ParseArray() { JsonValue value = JsonValue.Parse("[1,2,3,4,5]"); Assert.AreEqual(typeof(JsonArray), value.GetType()); Assert.AreEqual(5, value.Array.Items.Count); Assert.AreEqual(typeof(JsonNumber), value.Array[2].GetType()); Assert.AreEqual(new JsonNumber { Int = 3 }, value.Array[2].Number); JsonObject o = new JsonObject(); o["name"] = new JsonText { Value = "Lars" }; o["age"] = new JsonNumber { Int = 50 }; JsonArray a = new JsonArray(); a.Items.Add(o); JsonObject p = new JsonObject(); p["name"] = "Bodil"; Assert.AreEqual("Bodil", p["name"].Text.Value); p["age"] = 50; Assert.AreEqual <int>(50, p["age"]); p["husbond"] = o; a.Items.Add(p); string arrayText = a.ToString(); Assert.AreEqual(JsonValue.Parse(arrayText).Format(), a.Format()); Assert.AreEqual(100, 2 * a[1]["age"]); if (o["name"] != "Lars") { throw new InvalidProgramException(); } }
public void setContent(JsonText json, XmlText xml, string word) { originalText.text = word; if (buttonText.text == "Dict") { if (json != null) { translate.text = json.text[0]; Debug.Log("Translate: (" + json.lang + ") " + json.text[0]); // break; } } else { if (xml != null) { translate.text = "<b>" + word + "</b> [" + xml.pr + "] " + xml.fl + "\n <size=22>" + xml.sn + " " + xml.dt + "\n <i>" + xml.vi + "</i></size>"; Debug.Log("Dict"); //break; } } }