C# - parse JSON with dynamic and access property name with colon - c#

When getting a JSON with property with :
i.e.
{
"root": {
"sim:names": [{
"name": "Tom"
},
{
"name": "David"
}]
}
}
I'm using Newtonsoft Dynamic parse.
var data = JsonConvert.DeserializeObject<dynamic>(jsonString);
I'm trying to access
data.root.sim:names
But getting compilation error "Invalid expression term ':'"
How can I access it?

You should convert it to object
var data = JsonConvert.DeserializeObject<Object>(jsonString);
And access it like this:
var value = ((JObject)data)["root"]["sim:names"];

Related

Read value from nested Json object

I am trying to read a value from a nested Json object, but I am getting a Parse error:
My Json object:
{
"MessageId": "f6774927-37cf-4608-b985-14a7d86a38f9",
"Time": "2017-04-06T16:28:38.0719933+02:00",
"Data":
{
"ID":
{
"value": "0008044834"
},
"Carrier":
{
"value": 0
},
"Tool":
{
"value": 0
}
}
}
var myJsonString = File.ReadAllText(_currentDictory.FullName + #"\test\" + completeFilename);
var myJObject = JObject.Parse(myJsonString);
var serial = myJObject.SelectToken("Data.ID").Value<String>();
System.InvalidCastException
HResult=0x80004002
Message=Cannot cast Newtonsoft.Json.Linq.JObject to Newtonsoft.Json.Linq.JToken.
Source=Newtonsoft.Json
Reading other values such as "MessageID" works withou any problems, but as soon as I try to get "Data.XYZ" I am getting the error above.
You need to add value to your json path:
var serial = myJObject.SelectToken("Data.ID.value").Value<String>();
Your current path selects JObject containing one property named value and you can't convert it directly to string.
MessageId is a string. So you can directly read its value.
Data on the other hand contains objects (see the { and } ). Therefor you need to use
var serial = myJObject.SelectToken("Data.ID.value").Value<String>();
Also see:
Getting 'Cannot cast Newtonsoft.Json.Linq.JObject to Newtonsoft.Json.Linq.JToken' when retrieving items from JSON

C# JSON Deserialise / Get Data Pair from Data Name at Runtime

I want to create a method with the C# Newtonsoft library that can take in a parameter value to return the JSON data value, without needing to know and create a class beforehand, but all I can find are examples to deserialise into a class or into a dynamic object, both needing to know JSON structure prior at development time
Here's an example of what the kind of JSON format I'm expecting, but is subject to change:
{
"Input":
[
{
"Name": "foo"
},
{
"Name": "bar"
},
]
"Output":
[
{
"Name": "bob"
},
{
"Name": "builder"
},
]
}
I'm locked into using Newtonsoft library to work on the JSON file, or do it myself from scratch as it's an embedded system.
You can use JObject. If you deserialize a class without the type it will be deserialized to JObject. You would access your JObject values with named index which is obviously your property name. Other type of interest to you is JArray. This all resides in namespaces:
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
Example:
So the example with your JSON would be:
var json = #"{
""Input"":
[
{ ""Name"": ""foo"" },
{ ""Name"": ""bar"" }
],
""Output"":
[
{ ""Name"": ""bob"" },
{""Name"": ""builder""}
]
}";
var obj = JsonConvert.DeserializeObject(json) as JObject;
var input = obj["Input"] as JArray;
var inputArray = input[0]["Name"];
This would get the first element in array that is in Input field - "foo".

Deserialize dynamic object in c#

I am trying to fetch Facebook profile data through Graph API. I am using Facebook SDK in MVC application. Using the following code returns dynamic result.
dynamic myInfo = await fb.GetTaskAsync("v2.8/me?fields=first_name,last_name,link,locale,email,name,birthday,gender,location,age_range");
var facebookProfile = new FacebookProfileViewModel()
{
FirstName = myInfo.first_name,
LastName = myInfo.last_name,
LinkUrl = myInfo.link,
Locale = myInfo.locale };
I am getting the data from facebook like this -
[{"Key":"first_name","Value":"John"},{"Key":"last_name","Value":"Doe"},{"Key":"link","Value":"https://www.facebook.com/app_scoped_user_id/4327693/"}]
I am getting the following error -
Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: Cannot implicitly convert type 'Facebook.JsonObject' to 'string'
Install newtonsoft:
Install-Package Newtonsoft.Json
Convert from json:
string json =
"[
{
"Key": "first_name",
"Value": "John"
},
{
"Key": "last_name",
"Value": "Doe"
},
{
"Key": "link",
"Value": "https://www.facebook.com/app_scoped_user_id/4327693/"
}
]";
FbProfile Profile = JsonConvert.DeserializeObject<FbProfile>(json);

error deserialization dynamic json

I have the following Json , which has a dynamic set of values
[ {
"Type": "Animal" }, {
"Profession": "Dog" } ]
I want to read it into an object
List<List<KeyValuePair<String,String>>>
this works :
var objectList = JsonConvert.DeserializeObject<List<dynamic>>(rawStringJsonData);
but when I try
var objectList = JsonConvert.DeserializeObject<List<List<KeyValuePair<String,String>>>(rawStringJsonData);
I get an error
Additional information: Cannot deserialize the current JSON object
(e.g. {"name":"value"}) into type
You can read it as a List<Dictionary<string,string>> and then cast it to
List<List<KeyValuePair<String,String>>>
Try this:
var rawStringJsonData = "[ { \"Type\": \"Animal\" }, { \"Profession\": \"Dog\" } ]";
var dictList = JsonConvert.DeserializeObject<List<Dictionary<string,string>>>(rawStringJsonData);
List<List<KeyValuePair<string,string>>> objectList =
dictList.Select(i => i.ToList()).ToList();
If you use the debugger to inspect the type of your first try, its just deserializing to a list of JTokens, and seeing as that you want a list of key value pairs I'd say that not really anything useful.
The List<List<KeyValuePair<String,String>>> datatype does not match your data. That would maybe look something like this
[ {"Key": "Type", "Value": "Animal" }, {"Key": "Profession", "Value": "Dog" } ]
In this case I'd probably deserialize to a dictionary instead:
var objectList = JsonConvert.DeserializeObject<List<Dictionary<string,string>>>(rawStringJsonData);

Json to C# object with google spreadsheet

EDITED:
If I load a google spreadsheet using JSON URL into a dynamic C# object, I can't access some entries because the JSON looks like this:
"author": [
{
"name": {
"$t": "XYZ"
},
"email": {
"$t": "XYZ#gmail.com"
}
}
]
Why does the google JSON have $ namespaces? Can we remove them? What can be done?
Here is the code:
var json = new WebClient().DownloadString(#"GoogleUrlWithJson");
dynamic jsonObj = JsonConvert.DeserializeObject(json);
string a = jsonObj.feed.entry[0].author.name.$t; ==> Can't compile error "unexpected $"
Try using square bracket syntax to access the JSON property names that have $ in them:
string a = jsonObj.feed.entry[0].author.name["$t"];

Categories

Resources