public void MultipleSubscriptionOnDifferentKeys() { DataStream stream = new DataStream(); DataReceiver receiver = new DataReceiver(); DataReceiver receiver2 = new DataReceiver(); receiver.OnPayloadReceived((object p, string attribute, string label) => { JObject payload = (JObject)p; JObject actual = new JObject(); actual.Add("int", 2); actual.Add("string", "value"); foreach (var item in actual) { Assert.IsTrue(payload.ContainsKey(item.Key)); Assert.AreEqual(payload.GetValue(item.Key), item.Value); } Console.WriteLine(payload.GetType()); }); receiver2.OnPayloadReceived((object payload, string attribute, string label) => { Assert.AreEqual(5, payload); Assert.AreEqual(typeof(int), payload.GetType()); Console.WriteLine(payload.GetType()); }); receiver.Subscribe(stream, "hashtable", "JObject"); receiver2.Subscribe(stream, "int", "int"); stream.Parse(JSON); stream.DeliverSubscriptions(); }
public void ReceiveJObject() { DataStream stream = new DataStream(); DataReceiver receiver = new DataReceiver(); receiver.OnPayloadReceived((object p, string attribute, string label) => { JObject payload = (JObject)p; JObject actual = new JObject { { "int", 2 }, { "string", "value" } }; foreach (var item in actual) { Assert.IsTrue(payload.ContainsKey(item.Key)); Assert.AreEqual(payload.GetValue(item.Key), item.Value); } Console.WriteLine(payload.GetType()); }); receiver.Subscribe(stream, "hashtable", "JObject"); stream.Parse(JSON); stream.DeliverSubscriptions(); }
static public string getKeys(JObject jo, string prekey) { string ret = ""; Dictionary <string, object> dc = jo.ToObject <Dictionary <string, object> >(); foreach (string key in dc.Keys) { if (Object.ReferenceEquals(dc[key].GetType(), jo.GetType())) { if (prekey == "") { ret += getKeys((JObject)dc[key], key); } else { ret += getKeys((JObject)dc[key], prekey + "_" + key); } } else { if (prekey == "") { ret += "`" + key + "`" + ","; } else { ret += "`" + prekey + "_" + key + "`" + ","; } } } return(ret); }
/// <summary> /// 利用 jobject 更新对象 /// </summary> /// <param name="obj"></param> /// <param name="data"></param> public static void UpdateObject(this object obj, JObject data) { Type tt = obj.GetType(); // 利用反射,将data转成相应的数据 // https://stackoverflow.com/questions/5218395/reflection-how-to-get-a-generic-method var minfo = data.GetType() .GetMethods() .Where(m => m.Name == "ToObject") .Select(m => new { Method = m, Params = m.GetParameters(), Args = m.GetGenericArguments() }) .Where(x => x.Params.Length == 0 && x.Args.Length == 1) .Select(x => x.Method) .First(); minfo = minfo.MakeGenericMethod(new Type[] { tt }); var updatingObj = minfo.Invoke(data, new object[0]); // 查找待更新的keys var keys = data.Properties().AsQueryable().Select(p => p.Name).ToList(); var properties = tt.GetProperties().Where(p => keys.Contains(p.Name)); foreach (var prop in properties) { object value = prop.GetValue(updatingObj); // 给exist赋值 prop.SetValue(obj, value); } }
private static string GetQueryString(JObject obj) { var properties = from p in obj.GetType().GetProperties() where p.GetValue(obj, null) != null select p.Name + "=" + HttpUtility.UrlEncode(p.GetValue(obj, null).ToString()); return(String.Join("&", properties.ToArray())); }
public string Foo(JObject o) { // We're built against v9.0.1 of Json.NET, so you might expect // this to show that, but because of the plug-in host's assembly // resolver, we get a unified version Console.WriteLine(o.GetType().Assembly.FullName); return(""); }
private void button1_Click(object sender, EventArgs e) { treeView_json.Nodes.Clear(); TreeNode node = null; JObject jObject = JObject.Parse(textBox_json.Text); //添加异常处理 if (jObject.GetType() == typeof(Newtonsoft.Json.Linq.JObject)) { node = treeView_json.Nodes.Add("[Object]"); } else if (jObject.GetType() == typeof(Newtonsoft.Json.Linq.JArray)) { node = treeView_json.Nodes.Add("[Array]"); } foreach (var obj in jObject) { showJsonTree(treeView_json, jObject, obj.Key.ToString(), null, node); } }
public IEnumerator ConfigFieldInitializedAsEmpty() { yield return(null); var emptyJObject = new JObject(); Assert.That(ConfigManager.appConfig != null); Assert.That(ConfigManager.appConfig.config != null); Assert.AreEqual(ConfigManager.appConfig.config.GetType(), emptyJObject.GetType()); }
public ContactModel CreateContact(ContactModel contact) { HttpRequestMessage request = new HttpRequestMessage( method: HttpMethod.Post, requestUri: D365Client.BaseAddress + "defra_CreateContact"); JObject exeAction = new JObject(); if (contact.b2cobjectid != null) { exeAction["defra_b2cobjectid"] = contact.b2cobjectid; } if (contact.firstname != null) { exeAction["firstname"] = contact.firstname; } if (contact.lastname != null) { exeAction["lastname"] = contact.lastname; } if (contact.emailaddress1 != null) { exeAction["emailaddress1"] = contact.emailaddress1; } string paramsContent; if (exeAction.GetType().Name.Equals(value: "JObject", comparisonType: System.StringComparison.OrdinalIgnoreCase)) { paramsContent = exeAction.ToString(); } else { paramsContent = JsonConvert.SerializeObject(exeAction, new JsonSerializerSettings() { DefaultValueHandling = DefaultValueHandling.Ignore }); } request.Content = new StringContent(paramsContent); request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json"); var content = D365Client.SendAsync(request).Result; if (!content.IsSuccessStatusCode) { throw new WebFaultException(content.ReasonPhrase, (int)content.StatusCode); } ContactModel contactResponse = JsonConvert.DeserializeObject <ContactModel>(content.Content.ReadAsStringAsync().Result); return(contactResponse); }
public void JObject_is_formatted_as_application_json() { JObject obj = JObject.FromObject(new { value = 123, OtherValue = 456 }); var mimeType = Formatter.PreferredMimeTypeFor(obj.GetType()); var output = obj.ToDisplayString(JsonFormatter.MimeType); mimeType.Should().Be(JsonFormatter.MimeType); output .Should() .Be(@"{""value"":123,""OtherValue"":456}"); }
public ContactModel CreateContact(ContactModel contact) { HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, httpClient.BaseAddress + "defra_CreateContact"); //return new ServiceObject { ServiceUserID = UPN }; JObject exeAction = new JObject(); if (contact.b2cobjectid != null) { exeAction["defra_b2cobjectid"] = contact.b2cobjectid; } if (contact.firstname != null) { exeAction["firstname"] = contact.firstname; } if (contact.lastname != null) { exeAction["lastname"] = contact.lastname; } if (contact.emailaddress1 != null) { exeAction["emailaddress1"] = contact.emailaddress1; } string paramsContent; if (exeAction.GetType().Name.Equals("JObject")) { paramsContent = exeAction.ToString(); } else { paramsContent = JsonConvert.SerializeObject(exeAction, new JsonSerializerSettings() { DefaultValueHandling = DefaultValueHandling.Ignore }); } request.Content = new StringContent(paramsContent); request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json"); var content = httpClient.SendAsync(request).Result; if (!content.IsSuccessStatusCode) { throw new WebFaultException(content.ReasonPhrase, (int)content.StatusCode); } ContactModel contactResponse = JsonConvert.DeserializeObject <ContactModel>(content.Content.ReadAsStringAsync().Result); //ServiceObject returnObj = new ServiceObject() { ServiceUserID = contactResponse.contactid, ErrorCode = (int)contactResponse.HttpStatusCode, ErrorMsg = contactResponse.Message }; return(contactResponse); }
public static T Select <T>(this IEnumerable <T> enumerable, JObject jObject) where T : Model { MethodInfo selectMethod = typeof(T).GetMethod("Select", new Type[] { jObject.GetType() }); if (selectMethod != null) { return((T)selectMethod.Invoke(null, new object[] { jObject })); } if (jObject.ContainsKey("ID")) { return(enumerable.Select(jObject["ID"])); } return(null); }
private static string ValidateAndProcess <T>(IDataProcessor <T> processor, JObject dataObject) { string errors = string.Empty; ValidationResult validationResult = processor.Validator.Validate(dataObject); if (!validationResult.IsValid) { foreach (var error in validationResult.Errors) { errors += error.ErrorMessage + "\n"; } } else { try { var result = processor.Process(dataObject); if (result == null) { errors += "Failed to process object of type: " + dataObject.GetType() + " Reason: Processor failed to return valid DatabaseAction object"; } else { _queuedDBChanges.Enqueue(result); } } catch (Exception ex) { errors += "Failed to process object of type: " + dataObject.GetType() + " Reason: " + ex.ToMessageAndCompleteStacktrace(); } }; return(errors); }
static public string getValues(JObject jo) { string ret = ""; Dictionary <string, object> dc = jo.ToObject <Dictionary <string, object> >(); foreach (string key in dc.Keys) { if (Object.ReferenceEquals(dc[key].GetType(), jo.GetType())) { ret += getValues((JObject)dc[key]); } else { ret += "'" + dc[key].ToString() + "'" + ","; } } return(ret); }
public void Can_build_predicate_across_jobject_with_equality() { var b = new JsonQueryCompiler(); var d = new JObject() { ["Foo"] = "bar" }; var p = Expression.Parameter(d.GetType()); var e = b.Predicate(p, new JObject() { ["Foo"] = "bar" }); var r = (bool)e.Compile().DynamicInvoke(d); r.Should().Be(true); }
internal static ICollection<string> GetJsonKeys(JObject json) { Type jsontype = json.GetType(); FieldInfo fieldproperties = jsontype.GetField("_properties", BindingFlags.Instance | BindingFlags.NonPublic); if (fieldproperties != null) { var valueproperties = fieldproperties.GetValue(json); Type jPropertyKeyedCollection = valueproperties.GetType(); PropertyInfo keys = jPropertyKeyedCollection.GetProperty("Keys", BindingFlags.Instance | BindingFlags.GetProperty | BindingFlags.Public); if (keys != null) { var valuekeys = keys.GetValue(valueproperties, null); return (ICollection<string>) valuekeys; } } return null; }
public void test_0001_l2j() { JObject o = JObject.Parse(@"{ 'CPU': 'Intel', 'Drives': [ 'DVD read/writer', '500 gigabyte hard drive' ] }"); output.WriteLine($"o.GetType == {o.GetType()}"); JContainer jA = o as JContainer; output.WriteLine($"jA.GetType == {jA.GetType()}"); JToken jT = o as JToken; output.WriteLine($"jT.GetType == {jT.GetType()}"); // Start with plain one liner string cpu = (string)o["CPU"]; // Intel // Check out the types JToken jt = o["CPU"]; string cpu2 = jt.ToString(); cpu.Should().Be(cpu2); // plain string firstDrive = (string)o["Drives"][0]; // DVD read/writer // typed var jt2 = o["Drives"][0]; // Why does o also show up as JToken, not JArray or JContainer? // JArray : JContainer, IList<JToken>, ICollection<JToken>, IEnumerable<JToken>, IEnumerable string firstDrive2 = jt2.ToString(); firstDrive.Should().Be(firstDrive2); // plain IList <string> allDrives = o["Drives"].Select(t => (string)t).ToList(); IEnumerable <string> listDrives = o["Drives"].Select(t => (string)t); allDrives.Should().Equal(listDrives); }
public JObject CreateFromDTO <T1>(Document doc, JObject source, out T1 newElement) { JObject response; try { Type converterType = GetConverter(typeof(T1)); object converter = Activator.CreateInstance(converterType); newElement = (T1)converterType.GetMethod("CreateFromDTO").Invoke(converter, new object[] { doc, source }); response = new JObject(); response["OK"] = 1; } catch (Exception e) { newElement = default(T1); Exception ex = e.InnerException?.InnerException?.InnerException ?? e.InnerException?.InnerException ?? e.InnerException ?? e; response = new JObject(); response["ERROR"] = 1; response["Msg"] = e.Message.ToString(); response["Stack"] = e.StackTrace.ToString(); response["Inner"] = e.InnerException == null ? null : JObject.FromObject(new { Msg = e.InnerException.Message.ToString(), Stack = e.InnerException.StackTrace.ToString(), Inner = e.InnerException.InnerException == null ? null : JObject.FromObject(new { Msg = e.InnerException.InnerException.Message.ToString(), Stack = e.InnerException.InnerException.StackTrace.ToString() }) }); } response["Type"] = source.GetType().FullName; return(response); }
/// <summary> /// /// </summary> /// <returns></returns> public Contact UserInfo(Contact contact) { JObject exeAction = new JObject(); exeAction["firstname"] = contact.firstname; exeAction["lastname"] = contact.lastname; exeAction["emailid"] = contact.emailid; exeAction["UPN"] = contact.UPN; string paramsContent; if (exeAction.GetType().Name.Equals("JObject")) { paramsContent = exeAction.ToString(); } else { paramsContent = JsonConvert.SerializeObject(exeAction, new JsonSerializerSettings() { DefaultValueHandling = DefaultValueHandling.Ignore }); } HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, _resource + "api/data/v8.2/defra_UpsertContact"); request.Content = new StringContent(paramsContent); request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json"); HttpResponseMessage responseContent = ConnectToCRM(request); var content = responseContent.Content.ReadAsStringAsync().Result; Contact contactResponse = JsonConvert.DeserializeObject <Contact>(content); contactResponse.HttpStatusCode = contactResponse.Code == 0 ? responseContent.StatusCode : System.Net.HttpStatusCode.BadRequest; return(contactResponse); }
/// <summary> /// /// </summary> /// <param name="UPN"></param> /// <returns></returns> public Contact InitialMatch(string UPN) { JObject exeAction = new JObject(); exeAction["UPN"] = UPN; string paramsContent; if (exeAction.GetType().Name.Equals("JObject")) { paramsContent = exeAction.ToString(); } else { paramsContent = JsonConvert.SerializeObject(exeAction, new JsonSerializerSettings() { DefaultValueHandling = DefaultValueHandling.Ignore }); } //HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, _resource+ "api/data/v8.2/contacts?$select=contactid&$filter=defra_upn eq '"+UPN+"'"); HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, _resource + "api/data/v8.2/defra_InitialMatch"); request.Content = new StringContent(paramsContent); request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json"); HttpResponseMessage responseContent = ConnectToCRM(request); var content = responseContent.Content.ReadAsStringAsync().Result; Contact contactResponse = JsonConvert.DeserializeObject <Contact>(content); contactResponse.HttpStatusCode = contactResponse.Code == 0 ? responseContent.StatusCode : System.Net.HttpStatusCode.BadRequest; return(contactResponse); }
/// <summary> /// Broadcast a transaction Broadcasts a transaction and returns the transaction status /// </summary> /// <exception cref="ApiException">Thrown when fails to make API call</exception> /// <param name="body">The transaction payload to send</param> /// <returns>Task of ApiResponse (TransactionAnnounceResponseDTO)</returns> public async System.Threading.Tasks.Task <ApiResponse <string> > SendTransactionAsyncWithHttpInfo(JObject body) { // verify the required parameter 'body' is set if (body == null) { throw new ApiException(400, "Missing required parameter 'body' when calling TransactionRoutesApi->SendTransaction"); } var localVarPath = "/transaction/announce"; var localVarPathParams = new Dictionary <String, String>(); var localVarQueryParams = new List <KeyValuePair <String, String> >(); var localVarHeaderParams = new Dictionary <String, String>(Configuration.DefaultHeader); var localVarFormParams = new Dictionary <String, String>(); var localVarFileParams = new Dictionary <String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { "application/json" }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { "application/json" }; String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) { localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); } if (body != null && body.GetType() != typeof(byte[])) { localVarPostBody = Configuration.ApiClient.Serialize(body); // http body (model) parameter } else { localVarPostBody = body; // byte array } // make the HTTP request IRestResponse localVarResponse = (IRestResponse)await Configuration.ApiClient.CallApiAsync(localVarPath, Method.POST, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int)localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("SendTransaction", localVarResponse); if (exception != null) { throw exception; } } return(new ApiResponse <string>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (string)Configuration.ApiClient.Deserialize(localVarResponse, typeof(string)))); }
/// <summary> /// 获取类上的 JClassAttribute 注解的 java 类型名称 /// </summary> /// <param name="type">JObject继承类实例</param> /// <returns>java 类型名称</returns> internal static string Get(JObject jobject) { return JClassAttribute.Get(jobject.GetType()); }
public void JsonToDynamic(string strJson) { var tmp = JsonConvert.DeserializeObject <dynamic>(strJson); JObject tmp1 = tmp.Required.Leads; Console.WriteLine(tmp1.GetType()); var tmpIncrement = (JObject)tmp.Required.Leads.TimeAbsolute.Increment; string tmpValue = GetItemValue(tmpIncrement["Value"].ToString(), tmpIncrement["privatePrefix"].ToString()); string tmpUnit = GetItemValue(tmpIncrement["Unit"].ToString(), tmpIncrement["privatePrefix"].ToString()); var additionRoot = tmp.AdditionInfo.ECGAbout; //暂时不考虑单位的问题,而且其实单位应该也不会是问题,大部分情况都是统一的单位 GetItemValue(additionRoot.Heart_rate.Value.ToString(), additionRoot.Heart_rate.privatePrefix.ToString()); foreach (JProperty item in tmp1.Children()) { if (item.Name.Contains("LEAD")) { foreach (JProperty item2 in item.Value) { if (item2.Name == "Origin") { var valuePath = item2.Value["Value"]; } if (item2.Name == "Digits") { var digitsPath = item2.Parent["privatePrefix"].ToString(); } } } } var tmpJobj = (JObject)tmp.Required.Leads; int count1 = 0, count2 = 0; foreach (var item in tmpJobj) { if (item.Key.Contains("LEAD")) { foreach (JProperty item2 in item.Value) { if (item2.Name.Contains("Origin")) { string originUnit = item2.Value["Unit"].ToString(); } if (item2.Name.Contains("Digits")) { string digitPath = item2.Value.ToString(); } } } } var testSelector = GetTargetSelector(tmp.Required.Patient.BirthDay.Value, tmp.Required.Patient.privatePrefix.Value); GetNodeFromXml("test.xml", testSelector); }