Parsing JSON Data with C#

How can I deserialize JSON to a simple Dictionarystring,string in ASP.NET?

Json.NET does this...

string json = @"{""key1"":""value1"",""key2"":""value2""}";

var values = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);

More examples: Serializing Collections with Json.NET

Parsing json file in c# to get into all sections and properties

You can use the built-in JSON library in the .net core

using System.Text.Json;

add the following model definition

 public class Rootobject
{
public Company Company { get; set; }
}

public class Company
{
public Employee[] Employees { get; set; }
}

public class Employee
{
public string EmpName { get; set; }
public string EmpGender { get; set; }
public string Age { get; set; }
}

deserialize your object like the following

string jsonData = File.ReadAllText("data.json");
Rootobject ob = JsonSerializer.Deserialize<Rootobject>(jsonData);

now you have ob in you c# represent your JSON as C# object

I don't want to build a model for this

if you use Visual Studio you can auto generate your model classes required for your JSON as described here the above models are auto generated by Visual Studio

Parse JSON data from result with C#

The question has already been answered, but I think in a cumbersome way.

There is no point in converting the respnse to an object just for return it back to the same state (JSON).

you need return the reponse as it:

[HttpPost]
public ActionResult ProcessPreferences(string categoryTag, string userEmailAddr)
{
...

var response = acs.SendRequest("GET", getParameters);

return Content(response, "application/json");
}

Parse JSON data from file using C#

Your json has an issue its not an array and you are trying to parse it as an jarray,

this is how your json should look like

[
{
"Id": "92cb6271-005e-48e9-a319-a606b8b6e1ef",
"DefaultPosition": {
"PositionId": "35ed169a-1208-4d8a-8faa-d2627d5790ed",
"EntityDetails": {
"DateCreated": "2019-09-17T15:25:52.4942161-03:00",
"DateModified": "2019-09-17T15:45:28.896274-03:00",
"CreatedBy": {
"Id": "1abb5047-8580-4be1-909d-41138035e4c9",
"ItemDisplayText": "Laurete Araujo",
"ItemType": "Users"
},
"ModifiedBy": {
"Id": "1abb5047-8580-4be1-909d-41138035e4c9",
"ItemDisplayText": "Laurete Araujo",
"ItemType": "Users"
},
"Owner": {
"Id": "1abb5047-8580-4be1-909d-41138035e4c9",
"ItemDisplayText": "Laurete Araujo",
"ItemType": "Users"
}
},
"NameComponents": {
"FullName": "ABRAHÃO DOS SANTOS",
"FamilyName": "SANTOS",
"FirstName": "ABRAHÃO DOS"
},
"MaritalStatus": {
"Id": "97d7a9dd-a7c4-4076-829c-7ec63b0e3fe7",
"DisplayTitle": "Marital Status",
"ItemDisplayText": "Married",
"ItemType": "LookupListEntries"
}
}
}
]

or if you want to get the exact values without treating it as array then you can use this

public static void JsonParser(string file)
{
string fullname;
string gender;
string nationality;
string maritalstatus;

var json = System.IO.File.ReadAllText(file);

var objects = JObject.Parse(json);

fullname = (string)objects["DefaultPosition"]["NameComponents"]["FullName"];
Console.WriteLine(fullname);
Console.WriteLine("\n");
}

but the ideal approach should be creating a model that has the same structure and deserializing to that particular object.

Parsing JSON data in C#

I'm not sure how you are parsing the JSON string. Are you using a class in the Framework to do the deserialization?

You could use the JavaScriptSerializer Class defined in the System.Web.Script.Serialization Namespace (you may need to add a reference to System.Web.dll)

Using that class, you would write your code like this:

public class SContent
{
public string id { get; set; }
public SFrom from { get; set; }
}

public class SFrom
{
public string name { get; set; }
public string id { get; set; }
}

Then deserialization looks like this:

var json = new JavaScriptSerializer();
var result = json.Deserialize<SContent>(/*...json text or stream...*/);

See JavaScriptSerializer on MSDN. You might also want to check out this similar question.

Parsing Dynamic JSON in C#

Regarding your JSON string, you can use dynamic to parse it and access the data as shown below:

You can also find a working example at: https://dotnetfiddle.net/lnhwJz

using System;
using Newtonsoft.Json;


public class Program
{
public static void Main()
{
var jsonString=@"{'data':{'locationSuggestions':[{'location':{'id':{'value':'seekAnzPublicTest:location:seek:2dkY4vZJF'},'name':'Brisbane','contextualName':'Brisbane QLD 4000 AU','countryCode':'AU','parent':{'id':{'value':'seekAnzPublicTest:location:seek:2FjxhQans'},'name':'CBD & Inner Suburbs','parent':{'id':{'value':'seekAnzPublicTest:location:seek:32XZdsa2K'},'name':'Brisbane'}}}},{'location':{'id':{'value':'seekAnzPublicTest:location:seek:2ckmimaF1'},'name':'Brisbane Grove','contextualName':'Brisbane Grove NSW 2580 AU','countryCode':'AU','parent':{'id':{'value':'seekAnzPublicTest:location:seek:2UC23LszP'},'name':'Southern Highlands & Tablelands','parent':{'id':{'value':'seekAnzPublicTest:location:seek:FTwZdE2K'},'name':'New South Wales'}}}}]},'extensions':{'requestLatency':171}}";
var parsedData=JsonConvert.DeserializeObject<dynamic>(jsonString);

foreach(var item in parsedData.data.locationSuggestions)
{
Console.WriteLine(item.location.name);
Console.WriteLine(item.location.id.value);
Console.WriteLine(item.location.contextualName);
}
}
}

Output:

Brisbane 
seekAnzPublicTest:location:seek:2dkY4vZJF
Brisbane QLD 4000 AU
Brisbane Grove
seekAnzPublicTest:location:seek:2ckmimaF1
Brisbane Grove NSW 2580 AU

How can I parse some JSON dynamically without knowing JSON values?

The code below is perhaps not the most elegant nor complete, but I think it will get you going. I would start by using the JObject.Parse() from the Newtonsoft.Json.Linq namespace and take it from there.

JObject root = JObject.Parse(info);
string symbol = root["symbol"].ToObject<string>();
foreach (JToken toplevel in root["callExpDateMap"].Children())
{
foreach (JToken nextlevel in toplevel.Children())
{
foreach (JToken bottomlevel in nextlevel.Children())
{
foreach (JToken jToken in bottomlevel.Children())
{
JArray jArray = jToken as JArray;
foreach (var arrayElement in jArray)
{
InfoObject infoObject = arrayElement.ToObject<InfoObject>();
Console.WriteLine(infoObject.putCall);
Console.WriteLine(infoObject.exchangeName);
Console.WriteLine(infoObject.multiplier);
}
}
}
}
}

public class InfoObject
{
public string putCall { get; set; }
public string symbol { get; set; }
public string description { get; set; }
public string exchangeName { get; set; }
// ...
public int multiplier { get; set; }
// ...
}


Related Topics



Leave a reply



Submit