I need to take a JSON file and update/replace some objects of the JSON file. The problem is when I split the JSON into different JObject they are always null.
background:
I need to parse and update a JSON file with multiple objects based on ObservableCollection (can assume that class of the ObservableCollection will match perfectly the object in the JSON file). Here is a sample of the JSON
{
"Customers": [
{
"FirstName": "Bob",
"LastName": "Smith"
},
{
"FirstName": "Jane",
"LastName": "Doe"
}
],
"Subs":[
{
"SubID": "100",
"Descript": "Sub 1"
},
{
"SubID": "200",
"Descript": "Sub 2"
}
]
}
In my WPF application, there will be an ObservableCollection for Customers and Subs. So I figured that I could take the entire JSON, parse out the object that I need, do the updating, then updates the object to save the changes in the JSON like this;
JObject mainJson = JObject.Parse(File.ReadAllText("MyJSON.json"));
JObject cust = (JObject)mainJson["Customers"];
myColllection = JsonConvert.DeserializeObject<ObservableCollection<Customers>>(cust.ToString());
///Do update logic
cust = JObject.Parse(JsonConvert.SerializeObject(myColllection));
File.WriteAllText("MyJSON.json", mainJson.ToString());
Problem is that cust is always null. I cannot figure out what am I am doing wrong. Also, should I be doing this some other way?
The problem with your code is that mainJson["Customers"] is an array not a JObject. Change your code as
JArray cust = (JArray)mainJson["Customers"];
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.
I have a requirement to get the first set of records in c# JSON. Here is my JSON data for example
string sJSON = "{
{
"ID": "1",
"Name":"John",
"Area": "Java" ,
"ID": "2",
"Name": "Matt",
"Area": "Oracle" ,
"ID": "3","Name":
"Danny","Area": "Android"
}
}"
I need to extract only the 1st set of records (i.e. {{"ID": "1", "Name":"John", "Area": "Java"}}).
If there is only one record my code (see below) works fine but when there are multiple records it takes the last set of JSON data (i.e. {{"ID": "3","Name": "Danny","Area": "Android"}}).
JObject jsonObject = JObject.Parse(sJSON);
string sID = (string)jsonObject["ID"];
string sName = (string)jsonObject["Name"];
string sArea = (string)jsonObject["Area"];
Can anyone help me extract only the 1st set of JSON data?
You return the JSON data as JSON Array, now it is a simple JSON string.
If you're able to generate like below then you can easily get the single JSON element easily.
[{ "ID": "1", "Name":"John", "Area": "Java" },{ "ID": "2","Name": "Matt","Area": "Oracle" },{ "ID": "3","Name": "Danny","Area": "Android" } ]
Use the below link, to understand this JSON format.
http://json.parser.online.fr/
Parse the data as JToken.
Such that you have something like:
var jToken = JToken.Parse(sJSON);
var isEnumerable = jToken.IsEnumerable()
if(isEnumeable)
{
cast as JArray and get firstOrdefault
}
var isObject = jToken.IsObject();
if(isObject )
{
cast as JObject and perform straight casting
}
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
I have a data table witch i serialize into a json and then parse to my view code where i use J Query to get those values.
When i use
document.getElementById('Name').value = UserInfo.Name;
the
Userinfo.Name = null,
what am i doing wrong for not being able to read my UserInfo.
Could someone please tell me how i can get the values out of UserInfo.
Below is all my code:
C# Code:
public JsonResult SearchForUser(int id)
{
string Sjson = JsonConvert.SerializeObject(DataTable, Formatting.Indented);
return Json(Sjson, JsonRequestBehavior.AllowGet);
}
J Query code:
$.post("SearchForUser", { id: id }, function (UserInfo) {
if (UserInfo != "")
{
document.getElementById('Name').value = UserInfo.Name;
document.getElementById('Surname').value = UserInfo.Surname;
}
});
Json :
"[ {
"UserId": 5,
"UserName": "JamesBond#MI6.com",
"UserPassword": "007",
"Name": "James",
"RoleId": 2,
"EmployeeId": 5,
"Active": true,
"Name1": "James",
"Surname": "Bond",
"IdNumber": "007",
"PassportNumber": "700",
"PhysicalAddress": "MI6",
"PostalAddress": "MI7",
"TelNumber": "0126659007",
"SelNumber": "0837777007",
"EmailAddress": "JamesBond#MI6.com",
"Designation": "Spy",
"DateEmployedFrom": "2013-06-19T00:00:00",
"Active1": true } ]"
Extra:
I am working with MVC razor.
Thanks in advance.
Edit still can't access values (This edits are in reply with answers)
It looks like your JSON object is an array with one item. In that case you should be accessing UserInfo[0].Name. Also verify that document.getElementById('Name') does indeed find an element.
Also, since you're using jQuery, document.getElementById('Name') = UserInfo[0].Name could be rewritten as $('#Name').val(UserInfo[0].Name).
Use var info=jQuery.parseJSON(UserInfo); to parse the value and then info.Name will give you result
DEMO
Like your JSON object structure Check here