How to get element in JSON string - c#

I have this JSON string called assignee:
{
"id": 15247055788906,
"gid": "15247055788906",
"name": "Bo Sundahl",
"resource_type": "user"
}
I want to get the "name" element and its value if it's not null. I have tried
var jobject = JsonConvert.DeserializeObject<JObject>(assignee);
And
var jo = JObject.Parse(assignee);
I tried looping through it but I just get null exception or empty output even though if I just print the assignee variable itself its filled with data.
My loop is like:
foreach (var result in jobject["name"])
{
Debug.WriteLine(result);
}

The simplest and best way is to deserialise to a C# class, for example:
public class Data
{
public long Id { get; set; }
public string Name { get; set; }
//etc..
}
And deserialise like this
var data = JsonConvert.DeserializeObject<Data>(json);
var name = data.Name;

To get name use this
string name = jobject["name"];

Using ["name"] returns a JToken, it is null if the property doesn't exist
JToken token = jo["name"];
Debug.WriteLine(token?.ToString() ?? "<default value>");

If you don't know properties beforehand, you can loop through JObject properties and get name value pairs as following:
var jsonObject = JObject.Parse(str);
foreach (var item in jsonObject)
{
var name = item.Key;
JToken token = item.Value;
if (token is JValue)
{
var value = token.Value<string>();
}
}

Here is how it should work:
class Data
{
public long? Id { get; set; }
public string Gid { get; set; }
public string Name { get; set; }
public string Resource_Type { get; set; }
}
class Program
{
static void Main(string[] args)
{
string assignee = "{\"id\": 15247055788906, \"gid\": \"15247055788906\", \"name\": \"Bo Sundahl\", \"resource_type\": \"user\"}";
Data data = JsonConvert.DeserializeObject<Data>(assignee);
Console.WriteLine(data.Id);
Console.WriteLine(data.Gid);
Console.WriteLine(data.Name);
Console.WriteLine(data.Resource_Type);
Console.ReadLine();
}
}

Related

How to read json string in c#

I am trying to parse manually a string in json. This is how my json look like
{{
"dbViews": [
{
"viewID": 0,
"viewColumns": [
{
"dbTitle": "ColNmid",
"viewTitle": "string",
"activated": true,
"activatedLabel": "Afficher"
},
{
"dbTitle": "ColNmdelete",
"viewTitle": "string",
"activated": true,
"activatedLabel": "Afficher"
}
]
}
],
"AddViewName": "test"
}}
This is how i am trying to read it.
UserViewDto User = new UserViewDto();
dynamic obj = JObject.Parse(json);
User.id = obj.dbViews.viewID;
User.viewName = obj.AddViewName;
foreach (var item in obj.viewColumns)
{
if (obj.dbTitle == "ColNmid")
{
User.ColNmid = obj.viewTitle;
}
}
I can only read addViewName, i can't seem to access viewID or viewColumn.
Update:
after the comments I obviously miss the second array. Here my new code witch work
UserViewDto User = new UserViewDto();
dynamic obj = JObject.Parse(json);
User.viewName = obj.AddViewName;
foreach (var view in obj.dbViews)
{
User.id = view.viewID;
foreach (var item in view.viewColumns)
{
if (item.dbTitle == "ColNmid")
{
User.ColNmid = item.viewTitle;
}
}
}
Your json in question is invalid (extra { and } at start and end). It seems that you are using Newtonsoft's Json.NET library. Usual approach is to create model corresponding to your json structure and deserialize it:
public class Root
{
[JsonProperty("dbViews")]
public List<DbView> DbViews { get; set; }
[JsonProperty("AddViewName")]
public string AddViewName { get; set; }
}
public class DbView
{
[JsonProperty("viewID")]
public long ViewId { get; set; }
[JsonProperty("viewColumns")]
public List<ViewColumn> ViewColumns { get; set; }
}
public class ViewColumn
{
[JsonProperty("dbTitle")]
public string DbTitle { get; set; }
[JsonProperty("viewTitle")]
public string ViewTitle { get; set; }
[JsonProperty("activated")]
public bool Activated { get; set; }
[JsonProperty("activatedLabel")]
public string ActivatedLabel { get; set; }
}
var result = JsonConvert.DeserializeObject<Root>();
You don't need to include all properties in your class, you can include only needed ones.
If you don't want to create custom models and want to loop through the JObject properties in your case you can do it for example like that:
var jObj = JObject.Parse(json);
foreach(var view in jObj["dbViews"]) // dbViews is an array
{
Console.WriteLine(view["viewID"]);
foreach (var viewColumn in view["viewColumns"]) // viewColumns is an array
{
Console.WriteLine(viewColumn["dbTitle"]);
}
}

How to deserialize JSON using Newtonsoft Deserialize C#

I am trying to deserialize JSON file and want to assign to object ScanResult. var text showing all the values but scanresult showing null some null values. https://gyazo.com/ff2ce386f845394c458a88d43a1f30d8
please suggest if I am missing something.
//MY jSon File SCAN Test 1-1543045410222.json 's code
{
"at": 1543045410222,
"i": 1000,
"s": {
"Sensor1": ["OFF"],
"Sensor2": ["OFF"],
"DataReady1": ["OFF"],
"DataReady2": ["OFF"],
"CV1": [5.0],
"CV2": [6.0]
}
}
//ViewModel Code is as below:
public void ResendScanResult()
{
var ScanActivities = scanActivityManager.GetAll();
foreach (var item in ScanActivities)
{
var scanName = item.ScanName;
var dir = _dataFilePath + scanName + "\\";
var jsonFileName = string.Format("{0}{1}-{2}.json", dir, scanName, item.ScanDateEpoch);
string fileName = Path.GetFileName(jsonFileName);
// ScanResult scanResult = new ScanResult();
var text = File.ReadAllText(jsonFileName);
//var scanResults = JsonConvert.DeserializeObject<ScanResult>(text);
Common.Model.ScanResult scanResult = JsonConvert.DeserializeObject<Common.Model.ScanResult>(text);
var Mvm = MonitorViewModel.Instance;
// TargetProvider target = Mvm.GetTargetProvider(scanResult);
// Mvm.PublishToServer(target, scanResult);
}
}
and my scanRescult class code is as below :
namespace ABX.Common.Model
{
public class ScanResult
{
public ScanResult()
{
At = DateTimeOffset.Now.ToUnixTimeMilliseconds();
Interval = 1;
}
public string Name { get; set; }
public long At { get; set; }
public long Interval { get; set; }
public JObject Values { get; set; }
public string FileName { get; set; }
public JObject ToJson()
{
JObject json = new JObject
{
{ "at", At },
{ "i", Interval },
{ "s", Values }
};
return json;
}
Either rename your class properties to match your JSON, rename your JSON to match your class properties, or implement a custom JsonConverter, where you can implement arbitrary mapping.

How to get key name and its value whereas its value in also in the pair of key value form from json in C#

I am getting response in the format of JObject which is like this.
JObject response = JObject.Parse(account);
{
"status": 1,
"msg": "1 out of 1 Transactions Fetched Successfully",
"transaction_details": {
"ae6df74457a7cbf62caf": {
"mihpayid": "403993715518647003",
"request_id": "",
"bank_ref_num": "201833147408756",
"amt": "88.00",
"transaction_amount": "88.00",
"txnid": "ae6df74457a7cbf62caf",
"additional_charges": "0.00",
"Settled_At": "0000-00-00 00:00:00"
}
}
}
Now the "transaction_details" that value ("ae6df74457a7cbf62caf") rapidly change every transaction,So how i get that value and after that how I get "mihpayid" key value in C#.
You need to create a class to represent the JSON being returned.
The transaction_details part of the object can be represented as a Dictionary for example:
class Account
{
public int Status { get; set; }
public string Msg { get; set; }
public Dictionary<string, TransactionDetails> transaction_details { get; set; }
}
class TransactionDetails
{
public string mihpayid { get; set; }
public string requestid { get; set; }
public string bank_ref_num { get; set; }
public string amt { get; set; }
public string transaction_amount { get; set; }
public string txnid { get; set; }
public string additional_charges { get; set; }
public string Settled_At { get; set; }
}
And, instead of using JObject.Parse(...) use the JsonConvert.DeserializeObject to convert the JSON into your C# class:
var myData = JsonConvert.DeserializeObject<Account>(account);
You can now reference all the properties of your JSON using the myData object.
You can loop through the transaction_details reading each entry.
foreach(var item in myData.transaction_details)
{
var id = item.Key;
var transaction = item.Value;
var mihpayid = transaction.mihpayid;
}
The values of the variables in the for loop are:
id = the unique ID for each transaction i.e. "ae6df74457a7cbf62caf"
transaction = a Transaction object with all the values from the unique transaction
mihpayid = the mihpayid within the unique transaction i.e. "403993715518647003"
JObject response = JObject.Parse("{\r\n \"status\": 1,\r\n \"msg\": \"1 out of 1 Transactions Fetched Successfully\",\r\n \"transaction_details\": {\r\n \"ae6df74457a7cbf62caf\": {\r\n \"mihpayid\": \"403993715518647003\",\r\n \"request_id\": \"\",\r\n \"bank_ref_num\": \"201833147408756\",\r\n \"amt\": \"88.00\",\r\n \"transaction_amount\": \"88.00\",\r\n \"txnid\": \"ae6df74457a7cbf62caf\",\r\n \"additional_charges\": \"0.00\",\r\n \"Settled_At\": \"0000-00-00 00:00:00\"\r\n }\r\n }\r\n }");
JObject transaction = JObject.Parse(response["transaction_details"].ToString());
foreach(var token in transaction.Properties())
{
var rapidlyChangingId = token.Name;
Console.WriteLine("Rapidly Changing ID: " + rapidlyChangingId);
Console.WriteLine(transaction[rapidlyChangingId]);
}
OUTPUT:
Rapidly Changing ID: ae6df74457a7cbf62caf
{
"mihpayid": "403993715518647003",
"request_id": "",
"bank_ref_num": "201833147408756",
"amt": "88.00",
"transaction_amount": "88.00",
"txnid": "ae6df74457a7cbf62caf",
"additional_charges": "0.00",
"Settled_At": "0000-00-00 00:00:00"
}
You can use JObject and convert it to C# object. Something like this:
How to deserialize an JObject to .NET object

convert json String to datatable?

While converting json string datatable facing an issue with , (comma) value in value field.
actualy my json string is [{"BNo":"345","GNo":"3453","FirstName":"fjai","LastName":"ljai","Address":"BARETI,CEVO, 13/2","Telephone":"051682247","BirthDate":"23-Jan-1981","Email":""}]
In that please look at the address scenario "Address":"BARETI,CEVO, 13/2"
It has the , in the values field. While converting the string to data base i got error. Here the code which i used convert json string to datatable
public DataTable JsonStringToDataTbl(string jsonString)
{
DataTable dt = new DataTable();
string[] jsonStringArray = Regex.Split(jsonString.Replace("[", "").Replace("]", ""), "},{");
List<string> ColumnsName = new List<string>();
foreach (string jSA in jsonStringArray)
{
string[] jsonStringData = Regex.Split(jSA.Replace("{", "").Replace("}", ""), ",");
foreach (string ColumnsNameData in jsonStringData)
{
try
{
int idx = ColumnsNameData.IndexOf(":");
string ColumnsNameString = ColumnsNameData.Substring(0, idx - 1).Replace("\"", "");
if (!ColumnsName.Contains(ColumnsNameString))
{
ColumnsName.Add(ColumnsNameString);
}
}
catch (Exception ex)
{
throw new Exception(string.Format("Error Parsing Column Name : {0}", ColumnsNameData));
}
}
break;
}
foreach (string AddColumnName in ColumnsName)
{
dt.Columns.Add(AddColumnName);
}
foreach (string jSA in jsonStringArray)
{
string[] RowData = Regex.Split(jSA.Replace("{", "").Replace("}", ""), ",");
DataRow nr = dt.NewRow();
foreach (string rowData in RowData)
{
try
{
int idx = rowData.IndexOf(":");
string RowColumns = rowData.Substring(0, idx - 1).Replace("\"", "");
string RowDataString = rowData.Substring(idx + 1).Replace("\"", "");
nr[RowColumns] = RowDataString;
}
catch (Exception ex)
{
continue;
}
}
dt.Rows.Add(nr);
}
return dt;
}
The code must omit the , in the value field.. what can i do
If your keys are unknown at the time of being read, then you can use the JObject and the JProperty classes from JSON.Net to retrieve the keys and their values like this:
private void printKeysAndValues(string json)
{
var jobject = (JObject)((JArray)JsonConvert.DeserializeObject(json))[0];
foreach (var jproperty in jobject.Properties())
{
Console.WriteLine("{0} - {1}", jproperty.Name, jproperty.Value);
}
}
Applied to two different JSON input string, retrieves the key/value pair:
var json1 = #"[{""BNo"":""345"",""GNo"":""3453"",""FirstName"":""fjai"",""LastName"":""ljai"",""Address"":""BARETI,CEVO, 13/2"",""Telephone"":""051682247"",""BirthDate"":""23-Jan-1981"",""Email"":""""}]";
var json2 = #"[{""Test"": ""A"", ""Text"":""some text"", ""Numbers"":""123""}]";
printKeysAndValues(json1);
Console.WriteLine("-------------------");
printKeysAndValues(json2);
And the output is:
BNo - 345
GNo - 3453
FirstName - fjai
LastName - ljai
Address - BARETI,CEVO, 13/2
Telephone - 051682247
BirthDate - 23-Jan-1981
Email -
-------------------
Test - A
Text - some text
Numbers - 123
One possibility would be to use the dynamic keyword. You can directly access the field like this:
var json = #"[{""BNo"":""345"",""GNo"":""3453"",""FirstName"":""fjai"",""LastName"":""ljai"",""Address"":""BARETI,CEVO, 13/2"",""Telephone"":""051682247"",""BirthDate"":""23-Jan-1981"",""Email"":""""}]";
dynamic data = JsonConvert.DeserializeObject(json);
// take the first element of the array
string address = data[0].Address;
Console.WriteLine(address.Replace(",", " "));
The output is:
BARETI CEVO 13/2
Note that String.Replace does not fail, if the symbol that should be replaced is not currently present, so "test".Replace(",", " "); will return test.
Another possibility is to use the in ASP.NET build in JSON converter (serializer/deserializer) - NewtonSoft JSON.Net. You can use it in order to regain the structured data. You need to create a class that represents the JSON structure:
public class Data
{
public string BNo { get; set; }
public string GNo { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Address { get; set; }
public string Telephones { get; set; }
public string BirthDates { get; set; }
public string Emails { get; set; }
}
Then the current JSON can be converted to an object of type Data using the JsonConvert.DeserializeObject method:
var json = #"[{""BNo"":""345"",""GNo"":""3453"",""FirstName"":""fjai"",""LastName"":""ljai"",""Address"":""BARETI,CEVO, 13/2"",""Telephone"":""051682247"",""BirthDate"":""23-Jan-1981"",""Email"":""""}]";
// remove square braces [ and ] at the start resp. end
var data = JsonConvert.DeserializeObject<Data>(json.Substring(1).Substring(0, json.Length - 2));
Now you can access the Address field and for example replace the , symbol:
Console.WriteLine(data.Address.Replace(",", " "));
The output is:
BARETI CEVO 13/2
I think your service returns also the wrong JSON format. JSON always starts with an object (when not in JavaScript), meaning that everything at the top level must be enclosed within curly braces { and }. If the service should return an array, then it should look like this {"results": [{"BNo":"...},{...}]}. If you can't change the service, then you can adapt / correct the returned string. Add a typed model for the array:
public class DataHolder
{
public Data[] data { get; set; }
}
and then create a correct JSON object holding an array:
var data = JsonConvert.DeserializeObject<DataHolder>("{\"data\":" + json + "}");
Console.WriteLine(data.data[0].Address.Replace(",", " "));
The output is again the same.
You can convert the JSON value to C# objects using Newtonsoft. This would be easy for you. Once you have converted to the below object, you can easily modify the Address property to remove the ',' value.
public class RootObject
{
public string BNo { get; set; }
public string GNo { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Address { get; set; }
public string Telephone { get; set; }
public string BirthDate { get; set; }
public string Email { get; set; }
}
Use the below line to convert to C# object
var jsonString = "The output of your webservice";
var obj = Newtonsoft.Json.JsonConvert.DeserializeObject<RootObject>(jsonString);
Now obj instance holds the C# object which is very easy to manipulate.

Parse error with JSONObject in c# .net

I have a JSON file saved locally that is being opened and read from successfully, but every time I try to parse it it fails. I've checked the JSON online but I can't find fault with it.
{
"Groups": [
{
"UniqueId": "233619708",
"Title": "Partno",
"Customer": "Customer",
"Items": []
}
]
}
I'm using a modified version of the JSON reader included in a sample source in VS, which looks like this:
private async Task GetSampleDataAsync()
{
if (this._groups.Count != 0)
return;
StorageFile file = await Windows.Storage.KnownFolders.PicturesLibrary.GetFileAsync("DB.json");
string jsonText = await FileIO.ReadTextAsync(file);
if (jsonText == "") {
await new Windows.UI.Popups.MessageDialog("File Blank!").ShowAsync();
}
JsonObject jsonObject;
if(JsonObject.TryParse(jsonText, out jsonObject))
{ await new Windows.UI.Popups.MessageDialog("File Read Error! Json Couldn't Parse!").ShowAsync();
throw new FormatException(jsonText);
}
if(jsonObject.Count == 0)
{
return;
}
JsonArray jsonArray = jsonObject["Groups"].GetArray();
foreach (JsonValue groupValue in jsonArray)
{
JsonObject groupObject = groupValue.GetObject();
Part group = new Part(groupObject["UniqueId"].GetString(),
groupObject["Title"].GetString(),
groupObject["Customer"].GetString(),
groupObject["Description"].GetString());
foreach (JsonValue itemValue in groupObject["Items"].GetArray())
{
JsonObject itemObject = itemValue.GetObject();
group.Items.Add(new Box(itemObject["UniqueId"].GetString(),
Convert.ToInt16( itemObject["Qty"].GetNumber()),
itemObject["Location"].GetString(),
group.UniqueId));
}
this.Groups.Add(group);
}
}
Any ideas anyone? Every time JsonObject.TryParse runs it returns false, and JsonObject.Parse returns a KeyMissingException.
Thanks.
(btw, I know there's nothing in the items part, I've tried both with and without...)
Have you tried using the other Json conversion method?
JsonConvert.DeserializeObject(jsonText);
I remember from having to grab data from bitcoin API's that when one method didn't work as expected it was worth trying the other one.
I think it had something to do with JObject.Parse being for JSON Objects and JsonConvert.Deserialize being for JSON arrays.
EDIT:
This will parse and deserialize the JSON you provided.
public class MyJsonObject
{
public string UniqueId { get; set; }
public string Title { get; set; }
public string Customer { get; set; }
public string Description { get; set; }
public List<JsonObjectItem> Items { get; set; }
}
public class JsonObjectItem
{
public string UniqueId { get; set; }
public string Qty { get; set; }
public string Location { get; set; }
}
public void ParseJson(string jsonText)
{
JObject jsonObject = JObject.Parse(jsonText);
if(jsonObject != null)
{
JToken token = null;
if(jsonObject.TryGetValue("Groups", out token))
{
foreach (var partData in token.Children())
{
if (!partData.HasValues)
continue;
MyJsonObject obj = partData.ToObject<MyJsonObject>();
Part group = new Part(obj.UniqueId, obj.Title, obj.Customer, obj.Description);
if(obj.Items.Count > 0)
{
foreach (var item in obj.Items)
{
short qty;
if(!Int16.TryParse(item.Qty, out qty))
{
// Decide what to do if is error with parsing qty.
}
group.Items.Add(new Box(item.UniqueId, qty, item.Location, obj.UniqueId));
}
}
}
}
}
}
HOWEVER - Depending upon the exact make up of your 'Part' class, you may even be able to simplify this even further and change:
MyJsonObject obj = partData.ToObject<MyJsonObject>();
to:
Part group = partData.ToObject<Part>();
and that should populate the properties and list of items in one go.
Hope that is helpful

Categories

Resources