var details= _clientService.GetAsync<DoctorDetails>(getDetails).Result;
I get the Result from the service which is JSON when I use "object" in the GetAsync instead of DoctorDetails. However, I don't see any property values being filled in details (All are null in DoctorDetails). DoctorDetails is the cs file of the schema I generated through xsd.
DoctorDetails is an auto generated file that contains properties like
Name
ID etc
How to deserialize this and get values in those properties (in the details variable above)
Edit
It is only returning values if I make the syntax like this
var details= _clientService.GetAsync<object>(getDetails).Result;
If you haven't already tried this option, use a library called Json.Net from Newtonsoft for json stuff. Newtonsoft json.
Provided you have the schema details and the property names match you may try the following..
var details= _clientService.GetAsync<object>(getDetails).Result;//Please check if this is a string else use .ToString()
/*
"{
'Name': 'Doctor Who',
'ID' : '1001'
}";
*/
DoctorDetails m = JsonConvert.DeserializeObject<DoctorDetails>(details);
Documentation Deserialize an Object.
I'm not promoting this library, it's just a suggestion. :)
Hope it helps.
Related
Recently I've gotten into JSON parsing, and I was wondering, is it at all possible to completely dynamically load all of the contents within a JSON file? And by dynamically load, I mean, load all values of a JSON file without knowing any keys, meaning I cannot do the following code:
string contents = File.ReadAllText("SomeJsonFile.txt");
JObject obj = JObject.Parse(contents);
var value = obj["SomeKey"];
The reason I cannot do the code above, is because that would require the application to know the key ahead of time.
My goal is to be able to load any JSON file, and retrieve all values from said JSON file. I want to be able to load nested values, along with root values, all without knowing the keys.
Is there a way for me to do this? If you need any more information, please don't hesitate to ask.
The way I want to use this data is to first, bind a textbox to a string version of each key. Then I will dynamically add the TextBoxes to a FlowLayoutPanel, I also want the user to be able to change this data, and the JSON to change with it.
Please help.
If you don't know what the keys you are going to have you can use JArray from Json.NET to dynamically access the class.
See example instantiation and usage in the answer here:
How to access elements of a JArray (or iterate over them)
Assuming the JSON is an object and not an array, you could deserialize the json string to a IDictionary<string, object> using Json.NET
string myJsonString = File.ReadAllText("SomeJsonFile.txt");
var dataObj = JsonConvert.DeserializeObject<IDictionary<string, object>>(myJsonString);
var topLevelKeys = dataObj.Keys;
Your original question already shows you've successfully parsed a JSON string into a C# object, without knowing the keys.
It appears your actual question is on how to flatten the JObject into some kind of enumerable set of key/value pairs. For that, I refer you to the answers on this thread:
Generically Flatten Json using c#
Answer 2 IMO looks a lot cleaner:
string contents = File.ReadAllText("SomeJsonFile.txt");
var schemaObject = JObject.Parse(contents);
var values = schemaObject
.SelectTokens("$..*")
.Where(t => !t.HasValues)
.ToDictionary(t => t.Path, t => t.ToString());
I have the next issue: I receive a lot of JSONs in different formats. I need to process only part of these documents. I tried to use Newtonsoft.Json.Schema nuget, but got the next problem:
JSON how to don't parse additional properties
Can you suggest me some ways to parse only part of the JSON document, when we don't know structure of this json? We can store some schema of the document.
Example:
We have the next JSON document.
And here we need to process, for example, only name and age properties. And I will know these properties only in runtime.
{
'name': 'James',
'age': 29,
'salary': 9000.01,
'jobTitle': 'Junior Vice President'
}
If your json does not contain nested fields, so each of the top level fields are primitive types (not objects) then you can deserialize it as Dictionary<string, object> like this:
var fieldValueMap = JsonConvert.DeserializeObject<Dictionary<string, object>>(json);
string fieldName = "name";
Console.WriteLine(fieldValueMap.ContainsKey(fieldName)
? fieldValueMap[fieldName]
: "There is no such field");
Hey I trying to update existing document of ElasticSearch, I found a cURL code from Elasticsearch site
Note: Sam type with 2 document is already exists I just want to update a existing field
POST /EmployeeIndex/Sam/2/_update
{
"doc" : {
"Nested" : true,
"views": 0
}
}
Its working perfectly how I need but please help me to convert it to NEST, as i working on .NET, I managed to write a code
var responseUpdate = client.Update<clsEmployeeElasticSearch, object>(u => u
.Index("EmployeeIndex")
.Type("Sam")
.Id(2)
.Doc(new { Nested= true })
.RetryOnConflict(3)
.Refresh());
But it always creating a new field in my document instead of updating existing one.
Please see attached screenshot with a code
Please help guys.
What you need is a PartialUpdate. Applied on your example, the following code should do what you expect.
var responseUpdate = client.Update<clsEmployeeElasticSearch, object>(u => u
.Index("EmployeeIndex")
.Type("Sam")
.Id(2)
.Doc(new {IsActive ="true", Views="0"})
.DocAsUpsert()
);
Is it possible that you are already there but be just facing a casing missmatch issue? see from Nest reference:
Property Name Inference In many places NEST allows you to pass
property names and JSON paths as C# expressions, i.e:
.Query(q=>q
.Term(p=>p.Followers.First().FirstName, "martijn")) NEST by default will camelCase properties. So the FirstName property above
will be translated to "followers.firstName".
This can be configured by setting
settings.SetDefaultPropertyNameInferrer(p=>p); This will leave
property names untouched.
Properties marked with [ElasticAttibute(Name="")] or
[JsonProperty(Name="")] will pass the configured name verbatim.
...
Note that you are creating a dynamic object for the update so, i belive attributes might not a be a solution if you keep it that way
I have been trying to populate my variable bar with json fields from curl's POSTFIELDS attribute when invoking my workflow from an API using PHP. Below is a simple json passed when invoking the endpoint not as part of the URL but hidden POSTed data:
{"salesValue":5000,"authorId":2}
The properties above should be injected in Formatter Node where I generate the SQL statetement used by the ODBC driver to query our back-end database. I have been told that I can only do this, for now, by using the SCRIPT Node as I do not recall C# as having support for manipulating JSON Object out of the box. If I am behind with regards to that someone please lead me to an answer.
Question is: does Flowger support JSON Serialization, Deserialization, Decoding and/or encoding? There is a framework called JSON.Net for example. Can I use this if I want to manipulate my fgRequestBody property frfom my variable bar?
Try the below steps to get the desired results:
1 - Add a variable bar with two special properties: FgRequestBody and FgRequestContentType. Make sure that you specify the content type in the workflow, which will be application/json in your instance.
2 - Add a 'JSON Convert' directly after the start node and point your variable bar FgRequestBody to the input of Json on the Json Convert. This will convert json to xml.
3 - Add a 'XFormat' node and plug the xml output from the Json Convert to the 'XML Document' property. Right click on the node and add a new custom property with the name of the field that you would like to extract. In the custom property value, add the xpath to the value. In the Expression property of the node, add your sql statement e.g.
select * from tableName where name = '{customProperty}'
The results from this will be your sql query.
Troubleshooting Tip:
Use Postman Add-In (Chrome) or RESTClient (Firefox) to verify the results. You should see the node generation in the activity log within Flowgear. If you do not see this, then add a AllowedOrigin of * in your Flowgear Site properties. See the following for reference to this:http://en.wikipedia.org/wiki/Cross-origin_resource_sharing
I'm trying to define aoColumns using ajax and a C# webmethod. I am treating it very similarly to how I am passing in server-side data, using a List> data structure that I add rows of List to. My problem is that this results in a string like:
{\"aoColumns\":[[\"\\\"bVisible\\\": False\"],[\"\\\"bVisible\\\": True\"],[\"\\\"bVisible\\\": True\"],[\"\\\"bVisible\\\": True\"],[\"\\\"bVisible\\\": True\"],[\"\\\"bVisible\\\": True\"],[\"\\\"bVisible\\\": True\"],[\"\\\"bVisible\\\": True\"]]}
Which is nearly correct, except that the column definitions are using square brackets instead of {}. How would I go about generating the correct JSON text? Any help is greatly appreciated!
I am assuming you are using data tables from http://www.datatables.net/. Please correct me if I am wrong.
I am not sure I understand if you are having trouble creating the JSON string to return to the AJAX call or converting it into something usable on the server-side.
If you are going to create a JSON string in a web method, I would suggest using a Dictionary type, since they are so close to JSON strings. To convert a Dictionary type into a JSON string, use this:
var dictionary = new Dictionary<string, string>()
// add values here...
return new JavaScriptSerializer().Serialize(dictionary);
If you are converting a JSON string into a Dictionary object, use this:
var dictionary = new JavaScriptSerializer().Deserialize<Dictionary<string, string>>(jsonString);
Another thing I like to do is convert the dictionary into an array if I am going to be working with any keys or values since getting them from the dictionary can be a pain when you do not know the exact key value you want to work with.
For reference, the JavaScriptSerializer is part of the System.Web.Script.Serialization.JavaScriptSerializer namespace and in the System.Web.Extensions assembly.