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"];
Related
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".
I am converting XML to JSON.
Input:
<emp
id="17377"/>
<CustomerList>
<Customer
id="67149"/>
<Customer id="64260"/>
</CustomerList>
OutPut:
"emp": {
"id": "17377"
},
"CustomerList": {
"Customer": [
{
"id": "67149"
},
{
"id": "64260"
}
]
}
But I need the below output. But I can not remove <Customer from <CustomerList> in the input. Also Please note that I need accept dynamic name
of array input. But always i want to remove the inner property name to be removed. in this example its Customer.But I may get MarkList->Mark then I need to remove remove Mark, etc.,:
"emp": {
"id": "17377"
},
"CustomerList": [
{
"id": "67149"
},
{
"id": "64260"
}
]
Is this possible please.
I use below code to convert XML to Json:
var xml = new XmlDocument();
xml.XmlResolver = null;
xml.LoadXml(richTextBox1.Text);
var jsonText = JsonConvert.SerializeXmlNode(xml,Newtonsoft.Json.Formatting.Indented);
Note:
One solution would be find the char "[" and remove before "[" and after "{".
This is not possible, as it is simply trying to change to JSON scheme in which it was orignally built.
what you can do, is use JObject to change the value of customer to feet your needs:
JObject rss = JObject.Parse(json);
JObject customers = rss.SelectToken("CustomerList");
customers ["Customer"] = newValue;
This is the snippet, modify this in your code to feet your needs.
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"];
I have a little utility where we extract values from JSON using JObject.SelectToken(path). We need to determine the paths at run-time. Works perfectly.
What I now need to do is to write back into the JSON (JObject or other) using the same path string. I've hunted and searched and I can't quite find if there is anything that does this quite as cleanly as SelectToken does for reading.
(I'm also stuck in 3.5 CF)
For example, something like:
... JObject read in already ...
var theJToken = theJObject.SelectToken("animals.cat[3].name");
theTJoken.SetValue("Bob"); // Of course this doesn't exist
... serialize it ...
JToken.SelectToken actually returns a JToken which can be modified using JToken.Replace. You can use that to replace the node within your JSON object, mutating the original object.
JObject o = JObject.Parse(#"{ 'cats': [
{ 'name': 'cat 1' },
{ 'name': 'cat 2' },
{ 'name': 'cat 3' } ] }");
// get the token
JToken secondCatName = o.SelectToken("cats[1].name");
// replace the name
secondCatName.Replace("meow");
// and the original object has changed
Console.WriteLine(o.ToString());
// { "cats": [ { "name": "cat 1" }, { "name": "meow" }, { "name": "cat 3" } ] }
This is the JSON I get from a request on .NET:
{
"id": "110355660738",
"picture": {
"data": {
"url": "https://fbcdn-profile-a.akamaihd.net/hprofile-ak-prn2/1027085_12033235063_5234302342947_n.jpg",
"is_silhouette": false
}
}
}
and I'd like to catch the field "url", using (maybe?) LINQ. I do many request as this, that differents a bit. So I won't to create a C# Class and deserialize it every time.
Is it a way to extract a single field? Thank you!
No need for Linq, just use dynamic (using Json.Net)
dynamic obj = JObject.Parse(json);
Console.WriteLine((string)obj.picture.data.url);
Linq version would not be much readable
JObject jObj = JObject.Parse(json);
var url = (string)jObj.Descendants()
.OfType<JProperty>()
.Where(p => p.Name == "url")
.First()
.Value;
Documentation: LINQ to JSON
I would not recommend LINQ. I would recommend a JSON library such as newtonsoft.json.
So you can do this:
string json = #"{
""Name"": ""Apple"",
""Expiry"": "2008-12-28T00:00:00",
""Price"": 3.99,
""Sizes"": [
""Small"",
""Medium"",
""Large""
]
}";
JObject o = JObject.Parse(json);
string name = (string)o["Name"];
// Apple
JArray sizes = (JArray)o["Sizes"];
string smallest = (string)sizes[0];
// Small
Note:- this code has been copied from the samples present on the project site
http://james.newtonking.com/pages/json-net.aspx
In a bind you could always deserialize the JSON and serialize it to XML, and load the XML in a XDocument. Then you can use the classic Linq to XML. When you are done take the XML, deserialize it, and serialize it back to JSON to JSON. We used this technique to add JSON support to an application that was originally built for XML, it allowed near-zero modifications to get up and running.
You can easily query with LINQ like this
considering this JSON
{
"items": [
{
"id": "10",
"name": "one"
},
{
"id": "12",
"name": "two"
}
]
}
let's put it in a variable called json like this,
JObject json = JObject.Parse("{'items':[{'id':'10','name':'one'},{'id':'12','name':'two'}]}");
you can select all ids from the items where name is "one" using the following LINQ query
var Ids =
from item in json["items"]
where (string)item["name"] == "one"
select item["id"];
Then, you will have the result in an IEnumerable list