Converting "[myObject][1][application]" string to useable path on JObject - c#

First let me start off by showing you what I am trying to accomplish by using pseudo code. (Yes I know this example is not possible)
var path = "[DocInfo][Type]";
var doc = couchDbCall();
var specificProperty = doc[path];
I want to turn a string into a literaly path accessor in code but cannot seem to find any examples etc; probably due to my lack of a good search query.
{
"_id": "bb9f9e13-218a-4403-9920-79b0d353634b",
"_rev": "2-908d1257d7324a8b6f1c333cbefe2e41",
"Name": "conversionTest2",
"DocInfo": {
"Type": "Application",
"Platform": "test",
"Version": "12",
"VersionRelId": -1,
"Category": "Communications and Messaging",
"Created": {
"CreatedDate": "3/19/2015 7:56:07 PM",
"User": {
"Id": "bf51f6ce-d3f7-46ff-9ff0-c1e60c2ded44",
"Name": "Adrian Campos",
"Email": "adrian.campos#bizdox.com"
}
},
"Template": "Other Application",
"TemplateVersion": 0
}
}

Example with JSON.Net (get it via NuGet):
dynamic o = JsonConvert.DeserializeObject(yourJsonString);
string type = o.DocInfo.Type; // gets "Application"
var doc = couchDbCall();
var specificProperty = doc[type]; // assuming doc takes a string as key
UPDATE:
that works also:
string type = o["DocInfo"]["Type"];
UPDATE 2:
as far as I understand this little recursive method will help you out (note that there's no error handling whatsoever):
private string DoMyPaths(List<string> paths, JToken token)
{
string s = paths[0];
if (paths.Count > 1)
{
paths.RemoveAt(0);
JToken result = token[s];
return DoMyPaths(paths, result);
}
return token[s].ToString();
}
now you can pass in your path (delimited by '.'):
string myPath = "DocInfo.Created.User.Name";
var paths = myPath.Split('.').ToList();
dynamic o = JsonConvert.DeserializeObject(json);
var result = DoMyPaths(paths, o);
result:
"Adrian Campos"

Related

C# dynamic object, modify properties based on string paths

The use case is pretty simple in concept. I receive a json payload that has two properties on the root level:
instructions
base
Instructions are set of instructions that I am supposed to apply on the base json object.
For eg - according to the below payload,
I am supposed to traverse to the widgets within defaultWidgets of the base property.
Then replace it completely with whatever is the value of patchedValue.
Input Payload:
{
"instructions": [
{
"patchedPath": "defaultWidget.widgets",
"patchedValue": false,
}
],
"base": {
"defaultWidget": {
"hash": "ktocle2l0u527",
"layout": "6|6",
"managerId": "defaultWidget",
"widgets": [
{
"managerId": "defaultWidget",
"widgetId": "invCreateWid7",
"type": "standard",
"manifestPath": "nexxe.standard-section#0.0.0-next.11",
"defaultInputManifestPath": "nexxe.input#0.0.1-alpha.49",
"title": "scannedInvoice",
"children": [
{
"name": "tom"
}
],
"hash": "ktocle2lrgps9",
"directives": ""
}
]
}
}
}
The result should be :
{
"base": {
"defaultWidget": {
"hash": "ktocle2l0u527",
"layout": "6|6",
"managerId": "defaultWidget",
"widgets": false
}
}
}
Code:
var stringPayload = "{ \"instructions\": [ { \"patchedPath\": \"defaultWidget.widgets\", \"patchedValue\": false, } ], \"base\": { \"defaultWidget\": { \"hash\": \"ktocle2l0u527\", \"layout\": \"6|6\", \"managerId\": \"defaultWidget\", \"widgets\": [ { \"managerId\": \"defaultWidget\", \"widgetId\": \"invCreateWid7\", \"type\": \"standard\", \"manifestPath\": \"nexxe.standard-section#0.0.0-next.11\", \"defaultInputManifestPath\": \"nexxe.input#0.0.1-alpha.49\", \"title\": \"scannedInvoice\", \"children\": [ { \"name\": \"tom\" } ], \"hash\": \"ktocle2lrgps9\", \"directives\": \"\" } ] } }}";
var parsedPayload = JsonConvert.DeserializeObject(stringPayload);
var baseJ = parsedPayload.GetType().GetProperty("instructions").GetValue(parsedPayload, null);
string jsonString = JsonConvert.SerializeObject(parsedPayload);
I am stuck on the very initial steps , I am getting:
System.NullReferenceException: 'Object reference not set to an instance of an object.'
System.Type.GetProperty(...) returned null.
This is what QuickWatch says:
What's returned by DeserializeObject in this case is JObject so to start with you can cast to it:
var parsedPayload = (JObject) JsonConvert.DeserializeObject(stringPayload);
Then grab instructions and target to change:
var instructions = (JArray) parsedPayload["instructions"]; // cast to JArray
var result = parsedPayload["base"];
Then we can go over instructions and apply them:
foreach (var instruction in instructions) {
// grab target path and value
var targetPath = (string) ((JValue)instruction["patchedPath"]).Value;
var targetValue = (JValue)instruction["patchedValue"];
// temp variable to traverse the path
var target = result;
foreach (var part in targetPath.Split('.')) {
target = target[part];
}
// replace the value
target.Replace(targetValue);
}
Now result contains what was in base with instructions applied.
With Json.NET you can do that like this:
var json = File.ReadAllText("sample.json");
var semiParsedJson = JObject.Parse(json);
var instructions = (JArray)semiParsedJson["instructions"];
var #base = semiParsedJson["base"];
foreach (var instruction in instructions)
{
var path = (string)instruction["patchedPath"];
var newValue = (string)instruction["patchedValue"];
var toBeReplaced = #base.SelectToken(path);
toBeReplaced.Replace(newValue);
}
JObject.Parse parses the json string
With the index operator [] we retrieve the two top level nodes. - One of them is an array (that's why there is an explicit JArray cast)
The other one is a JToken
We iterate through the array and retrieve the path and the newvalue
We use the SelectToken to get the desired node and then apply the replacement via the Replace method.
Please bear in mind that this solution is not bulletproof. You might need to change the indexer operator to TryGetValue to be able to check existence before you perform any operation on the JToken.
You also need to check that the patchedPath is valid at all.

How to remove parent element from json in c#

How to covert the below json
{"data":{"id":12,"name":"jeremy","email":"jeremy#test.com"}}
to
{"id":12,"name":"jeremy","email":"jeremy#test.com"}
I want to remove the "data" element from json.
With json.net it's fairly straightforward
var input = "{\"data\":{\"id\":12,\"name\":\"jeremy\",\"email\":\"jeremy#test.com\"}}";
var result = JObject.Parse(input)["data"].ToString(Formatting.None);
Console.WriteLine(result);
Note : Formatting.None is only to preserve the formatting you had in your original example
Or Text.Json
var result = JsonDocument.Parse(input).RootElement.GetProperty("data").ToString();
Output
{"id":12,"name":"jeremy","email":"jeremy#test.com"}
Additional Resources
JObject.Parse Method (String)
Load a JObject from a string that contains JSON.
JObject.Item Property (String)
Gets or sets the JToken with the specified property name.
JToken.ToString Method (Formatting,JsonConverter[])
Returns the JSON for this token using the given formatting and
converters.
Formatting Enumeration
None 0 No special formatting is applied.
Text.Json
JsonDocument.Parse Method
Provides a mechanism for examining the structural content of a JSON
value without automatically instantiating data values.
JsonDocument.RootElement Property
Gets the root element of this JSON document
JsonElement.GetProperty Method
Gets a JsonElement representing the value of a required property
identified by propertyName.
I have a follow up question on a scenario where I don't want to remove the root element.
{
"keepMe": {
"removeMe": [
{
"id": "1",
"name": "Foo",
"email": "Foo#email.com"
},
{
"id": "2",
"name": "Bar",
"email": "Bar#email.com"
}
]
}
But I wanted it to look like
{
"keepMe": {
{
"id": "1",
"name": "Foo",
"email": "Foo#email.com"
},
{
"id": "2",
"name": "Bar",
"email": "Bar#email.com"
}
}
Using below would not work. Is there another way to do this?
var result = JObject.Parse(input)["keepMe"]["removeMe"].ToString(Formatting.None);
//{
// "id": "1",
// "name": "Foo",
// "email": "Foo#email.com"
//},
//{
// "id": "2",
// "name": "Bar",
// "email": "Bar#email.com"
//}
var result = JObject.Parse(input)["removeMe"].ToString(Formatting.None); //Null Reference
Found the answer using the SelectToken and Replace keyword
var jObj = JObject.Parse(input);
jObj.SelectToken("keepMe").Replace(jObj.SelectToken("keepMe.removeMe"));
string result = jObj.ToString();

'Accessed JObject values with invalid key value: 1. Object property name expected.'

I am trying to get JSON data from an api.
I have this json with me:
{
"elements": [
{
"id": 1,
"name": "Bob",
"address": "abc street",
"hobbies": {
"indoor": "Games, reading books",
"outdoor": ""
}
},
{
"id": 2,
"name": "Mark",
"address": "def street",
"hobbies": {
"indoor": "Games, reading books",
"outdoor": ""
}
}
]
}
I have this code with me:
using(var httpClient = new HttpClient()) {
HttpResponseMessage response = httpClient.GetAsync("api_url_here").Result;
var studentJsonString = response.Content.ReadAsStringAsync().Result;
var Jsresult = new JavaScriptSerializer().Deserialize<dynamic>(studentJsonString).ToString();
JObject jObject = JObject.Parse(Jsresult);
IEnumerable<dynamic> listDyn = jObject[0].Select(items => new StudentModel// gives error here as whole
{
id = items["id"].ToString(),
name = items["name"].ToString(),
address= items["address"].ToString()
});
}
But when I am calling the above method but it is giving me an error:
'Accessed JObject values with invalid key value: 1. Object property name expected.'
What am I missing?
Why are you deserializing twice? The result of
JavaScriptSerializer().Deserialize(customerJsonString)
is already an object. You don't need to parse it again with JObject.Parse(). You can just do
JObject jObject= JObject.Parse(customerJsonString)
Furthermore the result of JObject.Parse() is a dictionary and not an array. It has properties, which you can access by their names. For instance
jObject["elements"]
But of course, the compiler can't possibly predict, that jObject["elements"] will be an IEnumerable, so you will have to make sure of that.
jObject.Value<JArray>("elements").Select(item => ...)
This reads the property elements, of jObject as a JArray.

How to get root value of Json get from dialogflow?

I got the json response from dialogflow. Now I want to get the "q1" value. So I've tried this:
var stringjson = ApiAiJson<QueryResponse>.Serialize(queryResponse);
var deserializejson =ApiAiJson<QueryResponse>.Deserialize(stringjson);
if (deserializejson.Result.Action == "web.search")
{
JObject jsonob = JObject.Parse(stringjson);
string q = jsonob["parameters"]["q1"].ToString();
System.Console.WriteLine(q);
}
But string q returns "null".
Maybe the deserialisation is wrong. The value is embedded in parameters and not the root value. But I don't know how to get the root value of json.
Plus,here's the json response:
"result": {
"source": "agent",
"resolvedQuery": "search for apple",
"action": "web.search",
"actionIncomplete": false,
"parameters": {
"q1": "apple",
"q2": ""
},
Help!
Use below code:
q = jsonob["result"]["parameters"]["q1"].ToString();

C# get value from deserialized json object

I'm currently Deserializing a json string using the Newtonsoft.Json nuget packet using the following code:
var data = (JObject)JsonConvert.DeserializeObject(json);
Now I'm receiving an object in the following format:
{{ "meta": { "rap": 2098, "count": 5 }, "data": [ { "name": "Gold Tetramino of Mastery", "rap": 735, "uaid": "16601901", "link": "https://www.roblox.com/Gold-Tetramino-of-Mastery-item?id=5786047", "img": "https://t4.rbxcdn.com/081337d7ea86e6a406512aaa83bbcdeb", "serial": "---", "count": 1 }, { "name": "Silver Tetramino of Accomplishment", "rap": 385, "uaid": "16601900", "link": "https://www.roblox.com/Silver-Tetramino-of-Accomplishment-item?id=5786026", "img": "https://t1.rbxcdn.com/60da69cd76f8dad979326f63f4a5b657", "serial": "---", "count": 1 }, { "name": "Subzero Ski Specs", "rap": 370, "uaid": "155175547", "link": "https://www.roblox.com/Subzero-Ski-Specs-item?id=19644587", "img": "https://t4.rbxcdn.com/8ead2b0418ef418c7650d34103d39b6d", "serial": "---", "count": 1 }, { "name": "Rusty Tetramino of Competence", "rap": 319, "uaid": "16601899", "link": "https://www.roblox.com/Rusty-Tetramino-of-Competence-item?id=5785985", "img": "https://t2.rbxcdn.com/968ad11ee2f4ee0861ae511c419148c8", "serial": "---", "count": 1 }, { "name": "Bluesteel Egg of Genius", "rap": 289, "uaid": "16601902", "link": "https://www.roblox.com/Bluesteel-Egg-of-Genius-item?id=1533893", "img": "https://t7.rbxcdn.com/48bf59fe531dd1ff155e455367e52e73", "serial": "---", "count": 1 } ]}}
Now I'm trying to get the following value from it:
"rap": 2098,
I just need 2098 and I've been trying the following code:
string rap = data["rap"].Value<string>();
But sadly this wouldn't work. Does anyone have a idea how to get the value?
Try:
var result = data["meta"]["rap"].Value<int>();
or
var result = data.SelectToken("meta.rap").ToString();
or if you don't want to want to pass the whole path in, you could just search for the property like this:
var result = data.Descendants()
.OfType<JProperty>()
.FirstOrDefault(x => x.Name == "rap")
?.Value;
Instead of declaring as type var and letting the compiler sort it, declare as a dynamic and using the Parse method.
dynamic data = JArray.Parse(json);
Then try
data.meta.rap
To get the internal rap object.
I edited from using the deserializeobject method as i incorrectly thought that had the dynamic return type. See here on json.net documentation for more details: http://www.newtonsoft.com/json/help/html/QueryJsonDynamic.htm
I just came to add Yet another way to get 2098:
After having got your object in the way you actually did:
var data = (JObject)JsonConvert.DeserializeObject(json);
The first you have to note is that the value you want to get is itself a value of the property "meta":
so, first you have to extract the contents of "meta" by simply calling
data["meta"]
and just then you are able to ask for the Value<string> of "rap":
String rap = data["meta"].Value<string>("rap");
which acctually gives you the value you were looking for:
Console.WriteLine(rap); // 2098
var jobject = (JObject)JsonConvert.DeserializeObject(json);
var jvalue = (JValue)jobject["meta"]["rap"];
Console.WriteLine(jvalue.Value); // 2098
The value is actually an int type. Try:
int rap = data["rap"].Value<int>();
string rap = JsonConvert.DeserializeObject<dynamic>(json).meta.rap;
Console.WriteLine(rap); // 2098
If you're not into dynamic (or aren't using .NET 4+), I like how this other answer relies solely on Json.NET's API.
Try to use as following
var test = JsonConvert.DeserializeObject<dynamic>(param);
var testDTO = new TPRDTO();
testDTO.TPR_ID = test.TPR_ID.Value;
Note: For using of JsonConvert class you have to install Newton-Soft from your package-manager
the problem is that you are casting the deserialized json into a JObject. if you want to have the JObject then simple do this:
JObject.Parse(json);
then you have the JObject and you can access a specific path (for extracting value see this )
you have also another option which is to deserialize your json into a class that you have in your code like this:
var instanceOFTheClass = JsonConvert.DeserializeObject<YourClassName>(json);
with the above code you can access any property and values you want.
Use the enumerator to get at the value:
var data = (JObject)JsonConvert.DeserializeObject(json);
var enumerator = data.GetEnumerator();
enumerator.MoveNext();
var dataValue = enumerator.Current.Value.ToString();
Just use dynamic representation of object:
dynamic obj = JsonConvert.DeserializeObject(json)
var value = obj.meta.rap;
JObject easily convertable to dynamic type itself. You can either get string or int from this value:
var ivalue = (int)obj.meta.rap;
var svalue = (string)obj.meta.rap;

Categories