How to pass Json string with variable in c#? - c#

string a;
string b;
string jSonContent = #"{""fields"":{""summary"":""summary"" , ""description"": ""modified.""}}";
I want a instead of summary and b instead of modified. It works if I replace summary but gives errors if I replace both.
The edited code is, string jSonContent = #"{""fields"":{""summary"":"+ "\""+ a+ "\"" +" , ""description"": "+ "\""+ b+ "\"" +"}}"; It's not giving any error, summary field is getting updated, but the description field is not.
Please revert. Thanks!

I highly suggest you to use JSON library, for example Json.Net.
First of all, you'll be able to work with strongly typed objects, in addition you will avoid typos and similar bugs since the serializer will do the serialization for you.
public void Test()
{
string a = ""; //content of 'a' variable
string b = ""; //content of 'b' variable
var obj = new RootObject();
obj.Fields = new Fields();
obj.Fields.Summary = a;
obj.Fields.Description = b;
var jsonOutput = Newtonsoft.Json.JsonSerializer.Serialize(obj, typeof(RootObject));
}
public class Fields
{
[JsonProperty("summary")]
public string Summary { get; set; }
[JsonProperty("description")]
public string Description { get; set; }
}
public class RootObject
{
[JsonProperty("fields")]
public Fields Fields { get; set; }
}
Note: If you don't want to create unnecessary types, you can work directly with JObject, this is one of possible uses:
var jobj = Newtonsoft.Json.Linq.JObject.FromObject(new {
fields = new {
summary = a,
description = b
}
});
var jsonOutput = jobj.ToString();

string a = "a";
string b = "b";
string jSonContent = (#"{""fields"":{""summary"":""summary"" , ""description"": ""modified.""}}").Replace(#":""summary""", a).Replace("modified.", b);

You can use string.Format or string.concate Method
string jSonContent = string.Concat("{\"fields\":{\"summary\":","\"",a,"\" , \"description\": \"",b,"\"}}");

Use string fromat $""
String format allow you to replace values from your variables into a string. E.g.
string name = "Bruno";
string result = $"My name is {name}";
Console.WriteLine(result);
The output will be
My name is Bruno
In your case you just have to escape the json brackets with a double bracket {{
string a = "this is a sumary";
string b = "this is a description";
string jSonContent = $"{{\"fields\":{{\"summary\":\"{a}\" , \"description\": \"{b}\"}}}}";
Console.WriteLine(jSonContent);
the output is
{"fields":{"summary":"this is a sumary" , "description": "this is a description"}}
However I strongly advise to not build your json strings manually, use Json.NET or any other NuGet Packages.

Related

Parse JSON Objects with unique strings as parents using JSON.Net

Let's say I have this example JSON:
"Test": {
"KIf42N7OJIke57Dj6dkh": {
"name": "test 1"
},
"xsQMe4WWMu19qdULspve": {
"name": "test 2"
}
}
I want to parse this into an Array of a custom class I have, which will be exampled below:
class Class1 {
public string Name { get; set; }
Class1(string name) {
Name = name;
}
}
How can I parse this using Json.NET's JObject.Parse?
You can achieve your goal with JPath query like this :
var myArray = JObject
.Parse(json)
.SelectTokens("$.Test..name")
.Values<string>()
.Select(s => new Class1(s))
.ToArray();
But probably not the best way to do it.
I personnaly prefere to create classes to represent the json structure and then apply transformations.
void Main()
{
var json = #"{""Test"": {
""KIf42N7OJIke57Dj6dkh"": {
""name"": ""test 1""
},
""xsQMe4WWMu19qdULspve"": {
""name"": ""test 2""
}
}
}";
var root = JsonConvert.DeserializeObject<Root>(json);
var array = root.Test.Select(i => i.Value).ToArray();
array.Dump();
}
public class Root
{
public Dictionary<string, Class1> Test { get; set; }
}
public class Class1
{
public string Name { get; set; }
public Class1(string name)
{
Name = name;
}
}
To begin with, your Json is missing starting/closing braces. The Json needs to have wrapping braces around the Test value.
{
'Test':
{
'KIf42N7OJIke57Dj6dkh': {'name': 'test 1'},
'xsQMe4WWMu19qdULspve': {'name': 'test 2'}
}
}
If you are missing it in the original Json, you could wrap the current input Json as following.
var correctedJson = $"{{{inputJsonString}}}";
If you want to parse the Json Objects to Array of Class1 without creating additional concrete data structures and using JPath Queries, you could use Anonymous Types for the purpose using the DeserializeAnonymousType Method proved by Json.Net. For example,
var sampleObject = new {Test = new Dictionary<string,Class1>()};
var data = JsonConvert.DeserializeAnonymousType(correctedJson,sampleObject);
var result = data.Test.Select(x=>x.Value).ToArray();
You could also achieve it using JPath Query or creating Concrete Data Structures as #Kalten as described in his answer.

Parse JSON string to get a few reference data

How can I parse the given string in C#?
I want to extract the following values - username & ref_id
{
"User":{
"username":"Vinayaka",
"email":"Vinayaka#mindsol.in",
"ref_id":"43523543",
"state_code":"UP",
"active_status":"1",
"user_type":"Admin",
"last_active":"2018-09-22 13:50:23"
}
}
Here's four different ways of parsing your JSON using Newtonsoft.JSON which is one of the most common C# libraries to use for parsing JSON.
Example 1
Deserialization to our own class structure:
Usage:
Root output = JsonConvert.DeserializeObject<Root>(json);
var refId = output.SomeUser.ReferenceId;
Class structure:
/// <summary>
/// Class representing the JSON
/// </summary>
public class Root
{
[JsonProperty("User")]
public User SomeUser { get; set; }
public class User
{
[JsonProperty("username")]
public string UserName { get; set; }
[JsonProperty("email")]
public string EMail { get; set; }
[JsonProperty("ref_id")]
public string ReferenceId { get; set; }
// etc.
}
}
Example 2
Using dynamic types:
dynamic rootObject = JObject.Parse(json);
dynamic user = rootObject.User;
var refId = user.ref_id;
var username = user.username;
Example 3
Token/string property names and generic to extract value:
JObject root = JObject.Parse(json);
var refId = root["User"]["ref_id"].Value<string>();
var username = root["User"]["username"].Value<string>();
Example 4
Using select tokens:
var rootObject = JObject.Parse(json);
var refId = rootObject.SelectToken("User.ref_id");
var username = rootObject.SelectToken("User.username");
You can use System.Web.Script.Serialization.JavaScriptSerializer to parse string to JSON dynamic Object
Here is an example,
var jsonStr = #"{
""User"":{
""username"":""Vinayaka"",
""email"":""Vinayaka#mindsol.in"",
""ref_id"":""43523543"",
""state_code"":""UP"",
""active_status"":""1"",
""user_type"":""Admin"",
""last_active"":""2018-09-22 13:50:23""
}
}";
var json = new JavaScriptSerializer();
var data = json.Deserialize<dynamic>(jsonStr);
foreach(KeyValuePair<string,object> p in data["User"])
{
Console.WriteLine(string.Format("{0} : {1}", p.Key, p.Value));
}
You can also check for Newtonsoft.JSON
Alternatively, you may have a look at this "Quick and Dirty" approach.
Two simple methods:
static string QuickAndDirtyJsonLookupText(string json, string key) =>
QuickAndDirtyJsonFind(json, key).Split('"')[1];
static string QuickAndDirtyJsonFind(string json, string key) {
int keyIndex = json.IndexOf($"\"{key}\":");
if (keyIndex < 0)
throw new KeyNotFoundException($"Key \"{key}\" not found in '{json}'.");
return json.Substring(keyIndex + 3 + key.Length).TrimStart();
}
Lets you lookup what you need, for example:
const string json =
"{"+
" \"User\":{" +
" \"username\":\"Vinayaka\"," +
" \"email\":\"Vinayaka#mindsol.in\"," +
" \"ref_id\":\"43523543\"," +
" \"state_code\":\"UP\"," +
" \"active_status\":\"1\"," +
" \"user_type\":\"Admin\"," +
" \"last_active\":\"2018-09-22 13:50:23\"" +
" }" +
"}";
Assert.AreEqual("Vinayaka", QuickAndDirtyJsonLookupText(json, "username"));
Assert.AreEqual("43523543", QuickAndDirtyJsonLookupText(json, "ref_id"));
Of course, this is indeed "quick and dirty" and only works, if you know the structure of your json ahead of time, and if you know that the text values do not contain quotes - which is often the case. You can also easily add your own QuickAndDirtyJsonLookupInt, for instance.
If you want a more structured approach with full source code, check out my lightweight parser and generator on https://github.com/Dbquity/Json.

Get JSON Data in variable when only one item is returned

I am trying to get some currency values from an api. it's returning the data in the following format:
{"PKR_PKR":{"val":1}}
I want to show this value in textbox but there's an error
"Object reference not set to an instance of object".
I've tried the following code:
try
{
string endPoint = #"http:urlhere";
string ResultJson = "";
using (WebClient wc = new WebClient())
{
ResultJson = wc.DownloadString(endPoint);
}
JsonData values = JsonConvert.DeserializeObject<JsonData>(ResultJson);
txtBalanceRate.Text = values.CurrencyValue.ToString();
}
catch (Exception ex) { }
Class code:
class JsonData
{
public object CurrencyValue { get; set; }
}
**
UPDATE
**
Note: I can not update PKR_PKR Class becuase every time the name of variable is different for different currencies i.e. it can be USD_PKR , EUR_PKR etc
How can I resolve this?
FOLLOWING IS THE UPDATED CODE:
try
{
string endPoint = #"http://free.currencyconverterapi.com/api/v5/convert?q="+ddlCurrency.SelectedValue.ToString()+"_PKR&compact=y";
string ResultJson = "";
using (WebClient wc = new WebClient())
{
ResultJson = wc.DownloadString(endPoint);
}
RootObject rootObject = JsonConvert.DeserializeObject<RootObject>(ResultJson);
txtBalanceRate.Text = rootObject.PKR_PKR.val.ToString();
}
catch (Exception ex)
{
}
public class PKRPKR
{
public int val { get; set; }
}
public class RootObject
{
public PKRPKR PKR_PKR { get; set; }
}
If you are going to have dynamic object then you should try this out
dynamic data = Newtonsoft.Json.JsonConvert.DeserializeObject(json);
Type typeOfDynamic = data.GetType();
if( typeOfDynamic.GetProperties().Where(p => p.Name.Equals("PKR_PKR")).Any())
{
console.WriteLine(data.PKR_PKR.val);
}
else if( typeOfDynamic.GetProperties().Where(p => p.Name.Equals("USD_PKR")).Any())
{
console.WriteLine(data.USD_PKR.val);
}
else if( typeOfDynamic.GetProperties().Where(p => p.Name.Equals("EUR_PKR")).Any())
{
console.WriteLine(data.EUR_PKR.val);
}
above way is not tried and tested but you can have try like this as you json is dynamic.
Above way is checking property exist or not and get val from dynamci object
Your class structure is incorrect can you please try below class structure
public class PKRPKR
{
public int val { get; set; }
}
public class RootObject
{
public PKRPKR PKR_PKR { get; set; }
}
RootObject rootObject = JsonConvert.DeserializeObject<RootObject>(json);
Console.WriteLine(rootObject.PKR_PKR.val);
Mostly if you see above class structure , you josn each node is represent as class, but I dont go in much detail as Visual studio can do it for me.
When comes to json to object conversion ,I make use of utility provided by Visual studio. which does conversion of json string to proper class structure. here is image of it
Read how to do it full here :
Visual Studio Generate Class From JSON or XML
If you dont have visual studio with this feature you can use this online utility : json2csharp
Note: I can not update PKR_PKR Class becuase evert time the name of
variable is different for different currencies i.e. it can be USD_PKR
, EUR_PKR etc How can I resolve this?
SOLUTION
if json string {"PKR_PKR":{"val":1}} is fixed in your case, you can use following solution for any currency name you got.
static void Main(string[] args)
{
string json1 = "{ \"PKR_PKR\":{ \"val\":1}}";
string json2 = "{ \"USD_PKR\":{ \"val\":2}}";
string json3 = "{ \"EUR_PKR\":{ \"val\":3}}";
JToken token1 = (JToken)JsonConvert.DeserializeObject(json1);
Console.WriteLine(token1.First().First()["val"]);
JToken token2 = (JToken)JsonConvert.DeserializeObject(json2);
Console.WriteLine(token2.First().First()["val"]);
JToken token3 = (JToken)JsonConvert.DeserializeObject(json3);
Console.WriteLine(token3.First().First()["val"]);
Console.ReadLine();
}
I think your receiving object should contain a dictionary, not a single string:
Check this
Or you have to improve your object structure implementing a root item which contains a PKR_PKR sub object

Turn a list into JSON from an array

I am trying to convert a list to a json string. The json is generating fine, but when I try to generate an array within the JSON it won't format properly.
My list is generated
List<string> invoicesList = new List<string>();
foreach (var invoice in theInvoices)
{
invoicesList.Add(invoice.InvoiceNumber);
invoicesList.Add(String.Format("{0:c}", invoice.GrandTotal));
invoicesList.Add(FieldTranslation.ToShortDate(invoice.Date.ToString()));
}
Then I add it to the JSON
var info = new MobileAPIHelper.ClientPayrollInfo
{
GrossWages = String.Format("{0:c}", GrossWages),
InvoiceTotal = String.Format("{0:c}", invoiceTotal),
InvoiceDate = FieldTranslation.ToShortDate(invoiceDate.ToString()),
InvoiceList = invoicesList.ToArray()
};
The output ends up just being a long JSON string with everything from the list
"InvoiceList":["SALES000000000006","$9,300.00","4/11/2016","SALES000000000008","$4,650.00","12/22/2015"]
What I can't figure out is how to get the list / json to format that invoicelist like so:
"InvoiceList":[{
"SALES000000000006","$9,300.00","4/11/2016"
},{
"SALES000000000008","$4,650.00","12/22/2015"
}]
invoicesList is not a list of an object that contains those values, it's a list of strings. You need to make a class that acts as a container for
invoice.InvoiceNumber;
String.Format("{0:c}", invoice.GrandTotal);
invoice.Date.ToString());
these fields. Make invoicesList a list of that class, then parse it to json. You're adding raw strings.
If you make those string as object.
public class Invoice{
public string InvoiceNumber{get;set;}
public string GrandTotal{get;set;}
public string Date{get;set;}
}
List<Invoice> invoicesList = new List<Invoice>();
foreach (var invoice in theInvoices)
{
invoicesList.Add(new Invoice(){InvoiceNumber=invoice.InvoiceNumber,
GrandTotal= invoice.GrandTotal,
Date=FieldTranslation.ToShortDate(invoice.Date.ToString())});
}
Then there is a package called NewtonSoftJson which allows you to convert from Collection.
Go to package manager console (Click on view menu in visual studio-> Other windows -> Package Manager console)
Install-Package Newtonsoft.Json
C# code
var invoiceListString=JsonConvert.SerializeObject(invoicesList);
I will recommend to use NewtonSoft.Json.
public class Invoice
{
public string InvoiceNumber { get; set; }
public DateTime InvoiceDate { get; set; }
public string InvoiceTotal { get; set; }
}
public void PrintJson()
{
List<Invoice> InvoiceList = new List<Invoice>();
var outputObject = new { InvoiceList };
InvoiceList.Add(new Invoice { InvoiceNumber = "SALES0000001", InvoiceDate = DateTime.UtcNow, InvoiceTotal = String.Format("{0:c}", "90000") });
InvoiceList.Add(new Invoice { InvoiceNumber = "SALES0000002", InvoiceDate = DateTime.UtcNow, InvoiceTotal = String.Format("{0:c}", "60000") });
var output1 = JsonConvert.SerializeObject(outputObject);
var output2 = JsonConvert.SerializeObject(InvoiceList);
}
Output1
{"InvoiceList":[{"InvoiceNumber":"SALES0000001","InvoiceDate":"2017-02-22T16:46:31.6933956Z","InvoiceTotal":"90000"},{"InvoiceNumber":"SALES0000002","InvoiceDate":"2017-02-22T16:46:31.6933956Z","InvoiceTotal":"60000"}]}
Output2
[{"InvoiceNumber":"SALES0000001","InvoiceDate":"2017-02-22T16:46:31.6933956Z","InvoiceTotal":"90000"},{"InvoiceNumber":"SALES0000002","InvoiceDate":"2017-02-22T16:46:31.6933956Z","InvoiceTotal":"60000"}]
Please notice the Json in your question is not valid.
As pointed by Dispersia, your list is one big string list and, therefore, the json serializer behaves as requested -- turns this big string list into a big json string array.
I haven't got VS at hand to test the code below but try turning your invoice list into something like:
List<Tuple<String, String, String>> invoiceList = new List<>();
and then add tuples accordingly:
foreach (var invoice in theInvoices)
{
Tuple<String, String, String> t = new Tuple<>(
invoice.InvoiceNumber,
String.Format("{0:c}", invoice.GrandTotal),
FieldTranslation.ToShortDate(invoice.Date.ToString()));
invoicesList.Add(t);
}
Would that help?

Convert JSON String To C# Object

Trying to convert a JSON string into an object in C#. Using a really simple test case:
JavaScriptSerializer json_serializer = new JavaScriptSerializer();
object routes_list = json_serializer.DeserializeObject("{ \"test\":\"some data\" }");
The problem is that routes_list never gets set; it's an undefined object. Any ideas?
Or, you can use the Newtownsoft.Json library as follows:
using Newtonsoft.Json;
...
var result = JsonConvert.DeserializeObject<T>(json);
Where T is your object type that matches your JSON string.
It looks like you're trying to deserialize to a raw object. You could create a Class that represents the object that you're converting to. This would be most useful in cases where you're dealing with larger objects or JSON Strings.
For instance:
class Test {
String test;
String getTest() { return test; }
void setTest(String test) { this.test = test; }
}
Then your deserialization code would be:
JavaScriptSerializer json_serializer = new JavaScriptSerializer();
Test routes_list =
(Test)json_serializer.DeserializeObject("{ \"test\":\"some data\" }");
More information can be found in this tutorial:
http://www.codeproject.com/Tips/79435/Deserialize-JSON-with-Csharp.aspx
You probably don't want to just declare routes_list as an object type. It doesn't have a .test property, so you really aren't going to get a nice object back. This is one of those places where you would be better off defining a class or a struct, or make use of the dynamic keyword.
If you really want this code to work as you have it, you'll need to know that the object returned by DeserializeObject is a generic dictionary of string,object. Here's the code to do it that way:
var json_serializer = new JavaScriptSerializer();
var routes_list = (IDictionary<string, object>)json_serializer.DeserializeObject("{ \"test\":\"some data\" }");
Console.WriteLine(routes_list["test"]);
If you want to use the dynamic keyword, you can read how here.
If you declare a class or struct, you can call Deserialize instead of DeserializeObject like so:
class MyProgram {
struct MyObj {
public string test { get; set; }
}
static void Main(string[] args) {
var json_serializer = new JavaScriptSerializer();
MyObj routes_list = json_serializer.Deserialize<MyObj>("{ \"test\":\"some data\" }");
Console.WriteLine(routes_list.test);
Console.WriteLine("Done...");
Console.ReadKey(true);
}
}
Using dynamic object with JavaScriptSerializer.
JavaScriptSerializer serializer = new JavaScriptSerializer();
dynamic item = serializer.Deserialize<object>("{ \"test\":\"some data\" }");
string test= item["test"];
//test Result = "some data"
Newtonsoft is faster than java script serializer. ... this one depends on the Newtonsoft NuGet package, which is popular and better than the default serializer.
one line code solution.
var myclass = Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>(Jsonstring);
Myclass oMyclass = Newtonsoft.Json.JsonConvert.DeserializeObject<Myclass>(Jsonstring);
You can accomplished your requirement easily by using Newtonsoft.Json library. I am writing down the one example below have a look into it.
Class for the type of object you receive:
public class User
{
public int ID { get; set; }
public string Name { get; set; }
}
Code:
static void Main(string[] args)
{
string json = "{\"ID\": 1, \"Name\": \"Abdullah\"}";
User user = JsonConvert.DeserializeObject<User>(json);
Console.ReadKey();
}
this is a very simple way to parse your json.
Here's a simple class I cobbled together from various posts.... It's been tested for about 15 minutes, but seems to work for my purposes. It uses JavascriptSerializer to do the work, which can be referenced in your app using the info detailed in this post.
The below code can be run in LinqPad to test it out by:
Right clicking on your script tab in LinqPad, and choosing "Query
Properties"
Referencing the "System.Web.Extensions.dll" in "Additional References"
Adding an "Additional Namespace Imports" of
"System.Web.Script.Serialization".
Hope it helps!
void Main()
{
string json = #"
{
'glossary':
{
'title': 'example glossary',
'GlossDiv':
{
'title': 'S',
'GlossList':
{
'GlossEntry':
{
'ID': 'SGML',
'ItemNumber': 2,
'SortAs': 'SGML',
'GlossTerm': 'Standard Generalized Markup Language',
'Acronym': 'SGML',
'Abbrev': 'ISO 8879:1986',
'GlossDef':
{
'para': 'A meta-markup language, used to create markup languages such as DocBook.',
'GlossSeeAlso': ['GML', 'XML']
},
'GlossSee': 'markup'
}
}
}
}
}
";
var d = new JsonDeserializer(json);
d.GetString("glossary.title").Dump();
d.GetString("glossary.GlossDiv.title").Dump();
d.GetString("glossary.GlossDiv.GlossList.GlossEntry.ID").Dump();
d.GetInt("glossary.GlossDiv.GlossList.GlossEntry.ItemNumber").Dump();
d.GetObject("glossary.GlossDiv.GlossList.GlossEntry.GlossDef").Dump();
d.GetObject("glossary.GlossDiv.GlossList.GlossEntry.GlossDef.GlossSeeAlso").Dump();
d.GetObject("Some Path That Doesnt Exist.Or.Another").Dump();
}
// Define other methods and classes here
public class JsonDeserializer
{
private IDictionary<string, object> jsonData { get; set; }
public JsonDeserializer(string json)
{
var json_serializer = new JavaScriptSerializer();
jsonData = (IDictionary<string, object>)json_serializer.DeserializeObject(json);
}
public string GetString(string path)
{
return (string) GetObject(path);
}
public int? GetInt(string path)
{
int? result = null;
object o = GetObject(path);
if (o == null)
{
return result;
}
if (o is string)
{
result = Int32.Parse((string)o);
}
else
{
result = (Int32) o;
}
return result;
}
public object GetObject(string path)
{
object result = null;
var curr = jsonData;
var paths = path.Split('.');
var pathCount = paths.Count();
try
{
for (int i = 0; i < pathCount; i++)
{
var key = paths[i];
if (i == (pathCount - 1))
{
result = curr[key];
}
else
{
curr = (IDictionary<string, object>)curr[key];
}
}
}
catch
{
// Probably means an invalid path (ie object doesn't exist)
}
return result;
}
}
As tripletdad99 said
var result = JsonConvert.DeserializeObject<T>(json);
but if you don't want to create an extra object you can make it with Dictionary instead
var result = JsonConvert.DeserializeObject<Dictionary<string, string>>(json_serializer);
add this ddl to reference to your project: System.Web.Extensions.dll
use this namespace: using System.Web.Script.Serialization;
public class IdName
{
public int Id { get; set; }
public string Name { get; set; }
}
string jsonStringSingle = "{'Id': 1, 'Name':'Thulasi Ram.S'}".Replace("'", "\"");
var entity = new JavaScriptSerializer().Deserialize<IdName>(jsonStringSingle);
string jsonStringCollection = "[{'Id': 2, 'Name':'Thulasi Ram.S'},{'Id': 2, 'Name':'Raja Ram.S'},{'Id': 3, 'Name':'Ram.S'}]".Replace("'", "\"");
var collection = new JavaScriptSerializer().Deserialize<IEnumerable<IdName>>(jsonStringCollection);
Copy your Json and paste at textbox on json2csharp and click on Generate button.
A cs class will be generated use that cs file as below
var generatedcsResponce = JsonConvert.DeserializeObject(yourJson);
Where RootObject is the name of the generated cs file;
Another fast and easy way to semi-automate these steps is to:
take the JSON you want to parse and paste it here: https://app.quicktype.io/ . Change language to C# in the drop down.
Update the name in the top left to your class name, it defaults to "Welcome".
In visual studio go to Website -> Manage Packages and use NuGet to add Json.Net from Newtonsoft.
app.quicktype.io generated serialize methods based on Newtonsoft.
Alternatively, you can now use code like:
WebClient client = new WebClient();
string myJSON = client.DownloadString("https://URL_FOR_JSON.com/JSON_STUFF");
var myClass = Newtonsoft.Json.JsonConvert.DeserializeObject(myJSON);
Convert a JSON string into an object in C#. Using below test case.. its worked for me. Here "MenuInfo" is my C# class object.
JsonTextReader reader = null;
try
{
WebClient webClient = new WebClient();
JObject result = JObject.Parse(webClient.DownloadString("YOUR URL"));
reader = new JsonTextReader(new System.IO.StringReader(result.ToString()));
reader.SupportMultipleContent = true;
}
catch(Exception)
{}
JsonSerializer serializer = new JsonSerializer();
MenuInfo menuInfo = serializer.Deserialize<MenuInfo>(reader);
First you have to include library like:
using System.Runtime.Serialization.Json;
DataContractJsonSerializer desc = new DataContractJsonSerializer(typeof(BlogSite));
string json = "{\"Description\":\"Share knowledge\",\"Name\":\"zahid\"}";
using (var ms = new MemoryStream(ASCIIEncoding.ASCII.GetBytes(json)))
{
BlogSite b = (BlogSite)desc.ReadObject(ms);
Console.WriteLine(b.Name);
Console.WriteLine(b.Description);
}
Let's assume you have a class name Student it has following fields and it has a method which will take JSON as a input and return a string Student Object.We can use JavaScriptSerializer here Convert JSON String To C# Object.std is a JSON string here.
public class Student
{
public string FirstName {get;set:}
public string LastName {get;set:}
public int[] Grades {get;set:}
}
public static Student ConvertToStudent(string std)
{
var serializer = new JavaScriptSerializer();
Return serializer.Deserialize<Student>(std);
}
Or, you can use the System.Text.Json library as follows:
using System.Text.Json;
...
var options = new JsonSerializerOptions()
{
PropertyNameCaseInsensitive = true
});
var result = JsonSerializer.Deserialize<List<T>>(json, options);
Where T is your object type that matches your JSON string.
System.Text.Json is available in:
.NET Core 2.0 and above
.NET Framework 4.6.1 and above

Categories

Resources