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
Related
I have the following json called 'originalJson'
{
"user_active": true,
"user_firstname": "Bob",
"user_lastname": "Tester",
"user_displayname": "Bobby",
"user_primary_email": "bob#tester.com",
"user_login_enabled": true,
"user_profile": {
"user_locale": "en-gb",
"user_lang": "en-gb"
},
"user_identities": [],
"user_roles": [
{
"app_id": "74a019c9-7171-4af0-a773-3984edaa35ca",
"context_uuid": "74a019c9-7171-4af0-a773-3984edaa35ca",
"context_type": "context_application",
"role_oid": "test_role_a",
"role_start_date": "2020-06-27T13:00:00Z",
"role_end_date": "2021-06-27T13:00:00Z"
}
]
}
and I am trying to replace the role_start_date and role_end_date values.
I have tried the following
JObject jObj = JObject.Parse(originalJson);
jObj["user_roles"]["role_start_date"] = somenewstartDate;
jObj["user_roles"]["role_end_date"] = somenewendDate;
However it is failing and doesn't like the "jObj["user_roles"]["role_start_date"]". I thought it would be pretty simple to do, I must be missing something.
Any ideas?
The property "user_roles" is an array of objects not a single object. You are trying to set a property value in the first entry in that array, so you need to do:
jObj["user_roles"][0]["role_start_date"] = somenewstartDate;
jObj["user_roles"][0]["role_end_date"] = somenewendDate;
I am making rest call and receving following JSON response:
{
"issues": [{
"id": "250271",
"self": "KeyUrl1",
"key": "Key-8622",
"fields": {
"attachment": [{
"self": "AttachmentUrl1",
"id": "106198",
"filename": "export.htm"
}
],
"customfield_11041": "Test"
}
},
{
"id": "250272",
"self": "KeyUrl2",
"key": "Key-8621",
"fields": {
"attachment": [{
"self": "AttachmentUrl2",
"id": "106199",
"filename": "lmn.htm"
}
],
"customfield_11041": "Test"
}
},
]
}
I parsed it using NewtonSoft Json to JObject.
var jObject = JObject.Parse(response);
Further I am trying to filter such records where either attachment is missing or none of the attachments contain filename like "export".
Following is the code I have written, ideally it should result in just 1 record in the records object, however its returning both the objects.
var issues = jObject["issues"] as JArray;
var records = issues.Where(x => !x["fields"]["attachment"].Any() || !x["fields"]["attachment"].Any(y => y["filename"].Contains("export")));
Need help to figure out whats going wrong.
Here's fiddle link - https://dotnetfiddle.net/AVyIHr
The problem is that you're calling Contains("export") on the result of y["filename"], which isn't a string - it's a JToken. You need to convert to a string first, to use the form of Contains that you're expecting.
Additionally, you can get rid of the first condition - an issue with no attachments doesn't have any attachments with "export" filename anyway.
That leaves this:
var records = issues
.Where(x => !x["fields"]["attachment"].Any(y => ((string) y["filename"]).Contains("export")))
.ToList();
You may well find it's simpler to deserialize to a class, however - that will reduce the risk of typos and the risk of this sort of conversion error. If you deserialized to a List<Issue> you'd have a condition of:
x => !x.Fields.Attachments.Any(y => y.Filename.Contains("export"))
... which I think is rather cleaner.
var records = issues.Where(x => !x["fields"]["attachment"].Any() || !x["fields"]["attachment"].Any(y => y["filename"].ToString().Contains("export"))).ToList();
Add .ToString() will resolve the issue.
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
}
I am storing data in my cassandra database as string and i want to retrieve the string and convert it into json. i get an exception saying
An unhandled exception of type 'Newtonsoft.Json.JsonReaderException' happened
is there something wrong with the data stored ? or i am doing some other thing wrong ?
My query is :
INSERT INTO table2(key1,col1) values ('5',{'url':'{"hello":
{"hi":{"hey":"1","time":"5"}},
{"reg":{"hey":"1","time":"1"}},
{"install":{"hey":"0"}}},
"task":"1","retry":"00",
"max":"5","call":"140"'});
In my db when i click the map<text,text> column, it gets stored as :
{\"hello\":\r\n
{\"subscription_atrisk\":{\"hey\":\"1\",\"time\":\"100\"}},
{\"reg\":{\"hey\":\"1\",\"time\":\"2000\"}},
\"task\":\"0\",\"retry\":\"300\",\"max\":\"5\",\"call\":\"14400\"}
in my c# code, i try
string s = "{\"hello\":\r\n {\"subscription_atrisk\":{\"hey\":\"1\",\"time\":\"100\"}},{\"reg\":{\"hey\":\"1\",\"time\":\"2000\"}},\"task\":\"0\",\"retry\":\"300\",\"max\":\"5\",\"call\":\"14400\"";
Jobject json = Jobject.Parse(s); //Get an Error here.
Could anyone please throw some light on this ?
In JSON, an object should contain a key and either a value or another object/array.
You have syntax errors in your JSON object. First of all, always use double quotes.
Then... The url object has a key Hello but then where you are supposed to place two more keys, you're just putting there two more objects, as if it was an array.
This could be a correct syntax:
{
"url": {
"hello": {
"hi": {
"hey": "1",
"time": "5"
}
},
"MissingKey1":{
"reg": {
"hey": "1",
"time": "1"
}
},
"MissingKey2":{
"install": {
"hey": "0"
}
}
},
"task": "1",
"retry": "00",
"max": "5",
"call": "140"
}
Or if you really meant to have a hello object and an array of two more objects inside url:
{
"url": {
"hello": {
"hi": {
"hey": "1",
"time": "5"
}
},
"AnArray": [{
"reg": {
"hey": "1",
"time": "1"
}
}, {
"install": {
"hey": "0"
}
}]
},
"task": "1",
"retry": "00",
"max": "5",
"call": "140"
}
I suggest that before you store those JSON objects in the database, ALWAYS validate them to make sure that they're valid of syntax.
Or even better: this Newtonsoft library provides functions which serializes(creates) JSON strings from other objects. See JsonConvert.SerializeObject Method
In general it is a good idea to look around in the API documentation, it really can save you a lot of time so that you don't have to do unnecessary work.
Looks like you're missing a closing }
Try:
string s = "{\"hello\": {\"subscription_atrisk\":{\"hey\":\"1\",\"time\":\"100\"}}, \"missing_key\": {\"reg\":{\"hey\":\"1\",\"time\":\"2000\"}},\"task\":\"0\",\"retry\":\"300\",\"max\":\"5\",\"call\":\"14400\"}";
I'm getting the following Json format string as a result from a Facebook graph search request :
{
"data": [
{
"name": "Event A",
"start_time": "2013-11-08T19:00:00+0200",
"end_time": "2013-11-10T00:00:00+0200",
"timezone": "Europe/Bucharest",
"id": "232252355126"
},
{
"name": "Event B",
"start_time": "2013-11-08T13:00:00+0200",
"end_time": "2013-11-09T16:00:00+0200",
"timezone": "Europe/Bucharest",
"location": "Bucharest",
"id": "414334343426"
},
{
"name": "Event C",
"start_time": "2013-10-30T18:30:00+0200",
"timezone": "Europe/Bucharest",
"location": "Bucharest",
"id": "44315995273"
}
],
"paging": {
"previous": "https://graph.facebook.com/search?limit=3&type=event&q=Bucharest&since=1383930000&__paging_token=22251255126",
"next": "https://graph.facebook.com/search?limit=3&type=event&q=Bucharest&until=1383150600&__paging_token=44115995273"
}
}
I'm encountering some errors while trying to retrieve data from this JSON. I've tried with
dynamic jsonData = await facebookClient.GetTaskAsync(string.Format("https://graph.facebook.com/search?q={0}&type=event&limit={1}&offset={2}", locationKeyword, limit, offset));
dynamic result = JsonConvert.DeserializeObject(jsonData.ToString());
Some answers direct me to use JavaScriptSerializer but I don't have the namespace for that class, as I'm using API for developing Windows 8 Apps.
I can't manage how to get the events as somehow from data object.
I tried accessing the values in the immediate windows in VS as result.data but it's not working.
I search on how to make this but most answers seem to say to create a class in which the json data will fit.
Can't I achieve this with dynamic? (something like result.data.name, result.paging.previous etc)
I have done this exact thing before, except I converted into an XML, My Example:
(1 - JavaScript) var finalStr = JSON.stringify(facebookString)
(2 - ASP.NET) JsonConvert.DeserializeXmlNode("{\"root\":" + received_json + "}","root");
I managed at last to access the members...
To access name for example, or start_time, I did the following :
dynamic jsonData = await facebookClient.GetTaskAsync(string.Format("https://graph.facebook.com/search?q={0}&type=event&limit={1}&offset={2}", locationKeyword, limit, offset));
var result = JObject.Parse(jsonData.ToString());
var array = new JArray(result["data"]);
var a = array[0];
string name = (string) a.SelectToken("name");
var date = (DateTime?) a.SelectToken("start_time");
There might be better implementations but this one worked in my case. I posted it, in case it might be of help to others seeing this post.
Best wishes.