I am receiving response from httpWebRequest as a string, which is format of JSON. What I would like, is to change this string to json and then, there are two opitons
1) change json to the 2D array
2) change json to dictionary
The point is I want to have easy access to the variables.
This is a string I am receiving:
"[{\"Year\":2000,\"Name\":\"Ala\",\"Val\":0.5},{\"Year\":2001,\"Name\":\"Ola\",\"Val\":0.6}... {\"Year\":2004,\"Name\":\"Ela\",\"Val\":0.8}]"
So as you can see I could have table with n rows and 3 columns (Year, Name, Val).
This is the code which I use to receive the response
var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://127.0.0.1:5000/");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
//send request data in json format
streamWriter.Write(jsonData);
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
//take data as string
var result = streamReader.ReadToEnd();
}
return null;
}
Instead of null I will return this array/dictionary.
Which way is better? Someone know how to make it? I feel lost in c#.
Thank you for help in advance!
First, to make work with JSON easier you can install Newtonsoft.Json package
Install-Package Newtonsoft.Json -Version 11.0.2
Then add using Newtonsoft.Json;
Look at this example
public class Item
{
public int Year { get; set; }
public string Name { get; set; }
public double Val { get; set; }
}
public class Program
{
public static void Main()
{
string json = "[{\"Year\":2000,\"Name\":\"Ala\",\"Val\":0.5},{\"Year\":2001,\"Name\":\"Ola\",\"Val\":0.6},{\"Year\":2004,\"Name\":\"Ela\",\"Val\":0.8}]";
List<Item> items = JsonConvert.DeserializeObject<List<Item>>(json);
foreach(var item in items)
{
Console.WriteLine("Year: {0}; Name: {1}; Val: {2}", item.Year, item.Name, item.Val);
}
}
}
Here I create a new class Item witch will be represents one object from array from your JSON. Then using Newtonsoft.Json deserialize json string to list of items.
Related
I want to get the price value which is usd in this api and put it in a variable:
https://api.coingecko.com/api/v3/simple/price?ids=veco&vs_currencies=usd
I already tried this code but getting an error:
public static void StartGet()
{
HttpWebRequest WebReq = (HttpWebRequest)WebRequest.Create(string.Format(VECO.VecoPriceURL));
WebReq.Method = "GET";
HttpWebResponse WebResp = (HttpWebResponse)WebReq.GetResponse();
string jsonString;
using (Stream stream = WebResp.GetResponseStream())
{
StreamReader reader = new StreamReader(stream, System.Text.Encoding.UTF8);
jsonString = reader.ReadToEnd();
}
List<VECO.Coin> items = JsonConvert.DeserializeObject<List<VECO.Coin>>(jsonString);
foreach (var item in items)
{
Console.WriteLine(item.usd);
}
}
public class VECO
{
public static string VecoPriceURL = "https://api.coingecko.com/api/v3/simple/price?ids=veco&vs_currencies=usd";
public class Coin
{
public string usd { get; set; }
}
}
ERROR:
Newtonsoft.Json.JsonSerializationException: 'Cannot deserialize the current
JSON object (e.g. {"name":"value"}) into type
'System.Collections.Generic.List`1[ConsoleProgram.VECO+Coin]' because the
type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or
change the deserialized type so that it is a normal .NET type (e.g. not a
primitive type like integer, not a collection type like an array or List<T>)
that can be deserialized from a JSON object. JsonObjectAttribute can also be
added to the type to force it to deserialize from a JSON object.
Path 'veco', line 1, position 8.'
Your Data Structures needs to be slightly different.
public class Veco
{
public decimal usd { get; set; }
}
public class RootObject
{
public Veco veco { get; set; }
}
Please note that Json is a not an array or List, so you need to need List<> in the JsonConvert.DeserializeObject Method as well. Instead, you need to the following.
var result = JsonConvert.DeserializeObject<RootObject>(jsonString);
Example,
var jsonString = #"{'veco':{'usd':0.01558532}}";
var result = JsonConvert.DeserializeObject<RootObject>(jsonString);
Console.WriteLine($"USD Rate : {result.veco.usd}");
Output
USD Rate 0.01558532
Rewriting your method,
public static void StartGet()
{
HttpWebRequest WebReq = (HttpWebRequest)WebRequest.Create(string.Format(VECO.VecoPriceURL));
WebReq.Method = "GET";
HttpWebResponse WebResp = (HttpWebResponse)WebReq.GetResponse();
string jsonString;
using (Stream stream = WebResp.GetResponseStream())
{
StreamReader reader = new StreamReader(stream, System.Text.Encoding.UTF8);
jsonString = reader.ReadToEnd();
}
var item = JsonConvert.DeserializeObject<RootObject>(jsonString);
Console.WriteLine(item.veco.usd);
}
Update
Based on your comment, I would rewrite your method as follows. You no longer need the data structure.
public static void StartGet(string id)
{
var url = $"https://api.coingecko.com/api/v3/simple/price?ids={id}&vs_currencies=usd";
HttpWebRequest WebReq = (HttpWebRequest)WebRequest.Create(url);
WebReq.Method = "GET";
HttpWebResponse WebResp = (HttpWebResponse)WebReq.GetResponse();
string jsonString;
using (Stream stream = WebResp.GetResponseStream())
{
StreamReader reader = new StreamReader(stream, System.Text.Encoding.UTF8);
jsonString = reader.ReadToEnd();
}
var result = JsonConvert.DeserializeObject<JToken>(jsonString);
Console.WriteLine($"For {id},USD Rate : {result[id].Value<string>("usd")}");
}
Now you can use the method as follows
StartGet("veco");
StartGet("eos");
StartGet("uraniumx");
Output
For veco,USD Rate : 0.01581513
For eos,USD Rate : 2.42
For uraniumx,USD Rate : 0.890397
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
I'm trying to serialize an object(Item) to a file that gets appended with more Item objects each time the function is called.
It keeps giving me this error:
07-12 15:43:27.931 I/MonoDroid(17468): Newtonsoft.Json.JsonSerializationException: Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[WaterApp.Item]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
07-12 15:43:27.931 I/MonoDroid(17468): To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object.
Here is the object class:
using System;
using System.Collections;
using Android.Content;
using Android.Preferences;
using Java.IO;
namespace WaterApp
{
public class Item
{
public bool Type { get; set; }
public string ItemName { get; set; }
public DateTime ExpiryDate { get; set; }
public int ItemIconNumber { get; set; }
public Item(bool type, string itemName, DateTime expiryDate, int itemIconNumber)
{
Type = type;
ItemName = itemName;
ExpiryDate = expiryDate;
ItemIconNumber = itemIconNumber;
}
}
}
Here is the class where the data handling is done with methods:
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using Newtonsoft.Json;
using Console = System.Console;
using Environment = System.Environment;
using File = System.IO.File;
using JsonWriter = Newtonsoft.Json.JsonWriter;
namespace WaterApp.Droid
{
public abstract class DataHandler
{
private static string documentsPath = System.Environment.GetFolderPath(Environment.SpecialFolder.Personal);
private static string filePath = Path.Combine(documentsPath, "HatchListData.json");
public static void SaveObjectToFile(Item item)
{
// read in the existing list
// IMPORTANT - if this is the first time and the file doesn't exist, then
// you need to initialise itemList = new List<Item>();
var itemList = new List<Item>();
File.WriteAllText(filePath, String.Empty);
string json = File.ReadAllText(filePath);
itemList = JsonConvert.DeserializeObject<List<Item>>(json);
// add a new item
itemList.Add(item);
// serialize the list and write it out again
json = JsonConvert.SerializeObject(itemList, Formatting.Indented);
File.WriteAllText(filePath, json);
Console.WriteLine(File.ReadAllText(filePath));
}
public static void LoadList(List<Item> listToBeLoaded)
{
string json = "";
if (File.Exists(filePath))
{
if (filePath.Length > 2)
{
Console.WriteLine("READING" + "READ!");
using (StreamReader streamReader = new StreamReader(filePath))
{
string json = streamReader.ReadToEnd();
listToBeLoaded = JsonConvert.DeserializeObject<List<Item>>(json);
}
Console.WriteLine("READING" + "loaded");
}
}
else
{
Console.WriteLine("READING" + "Doesn't exist, json file.");
}
}
}
}
Please can someone push me in the right direction or help fix this error in any way? I'm not too sure how to fix the issue of the error. I don't understand what code the error is asking for.
you can't just append two serialized json objects together - that won't produce valid json. Instead, you need to read in the existing list, add the items to it, and then serialize it out again
// read in the existing list
// IMPORTANT - if this is the first time and the file doesn't exist, then
// you need to initialise itemList = new List<Item>();
json = File.ReadAllText(filePath);
var itemList = JsonConvert.DeserializeObject<List<Item>>(json);
// add a new item
itemList.Add(newItem);
// serialize the list and write it out again
string json = JsonConvert.SerializeObject(itemList, Formatting.Indented);
File.WriteAllText(path,json);
I want to convert this JSON return from php file into c#. But as a newbie don't know how, please help.
{"response": [
{"user_id":"26","crtloc_lat":"47.678238","crtloc_lng":"-122.131416"},
{"user_id":"27","crtloc_lat":"9.350192","crtloc_lng":"-95.391006"},
{"user_id":"28","crtloc_lat":"47.678238","crtloc_lng":"-122.131416"}
]}
The above JSON is returned from my PHP file.
WebRequest request = WebRequest.Create("http://localhost/abh/returntest.php");
WebResponse response = await request.GetResponseAsync();
List<Response> json ;
using (var stream = new StreamReader(response.GetResponseStream()))
{
json = JsonConvert.DeserializeObject<List<Response>>(stream.ReadToEnd());
}
foreach (var item in json)
{
Console.WriteLine("id={0},latitude={1},longitude={2}",item.user_id,item.crtloc_lat,item.crtloc_lng);
}
The Classes I am using are:
public class Response
{
public string user_id { get; set; }
public string crtloc_lat { get; set; }
public string crtloc_lng { get; set; }
}
public class RootObject
{
public List<Response> response { get; set; }
}
I am getting this error:
Cannot deserialize the current JSON object (e.g. {"name":"value"})
into type 'System.Collections.Generic.List`1[afterall.Response]'
because the type requires a JSON array (e.g. [1,2,3]) to deserialize
correctly.
The following line is wrong based on your sample JSON.
json = JsonConvert.DeserializeObject<List<Response>>(stream.ReadToEnd());
Try changing it to:
json = JsonConvert.DeserializeObject<RootObject>(stream.ReadToEnd());
Edit:
WebRequest request = WebRequest.Create("http://localhost/abh/returntest.php");
WebResponse response = await request.GetResponseAsync();
RootObject json;
using (var stream = new StreamReader(response.GetResponseStream()))
{
json = JsonConvert.DeserializeObject<RootObject>(stream.ReadToEnd());
}
foreach (var item in json)
{
Console.WriteLine("id={0},latitude={1},longitude={2}",item.user_id,item.crtloc_lat,item.crtloc_lng);
}
rewrite the following line :
json = JsonConvert.DeserializeObject<List<Response>>(stream.ReadToEnd());
as
json = JsonConvert.DeserializeObject<Response>(stream.ReadToEnd());
From your testlink in the comment of your post. Your response is not:
{"response": [
{"user_id":"26","crtloc_lat":"47.678238","crtloc_lng":"-122.131416"},
{"user_id":"27","crtloc_lat":"9.350192","crtloc_lng":"-95.391006"},
{"user_id":"28","crtloc_lat":"47.678238","crtloc_lng":"-122.131416"}
]}
as you post but rather:
connected{"response": [
{"user_id":"26","crtloc_lat":"47.678238","crtloc_lng":"-122.131416"},
{"user_id":"27","crtloc_lat":"9.350192","crtloc_lng":"-95.391006"},
{"user_id":"28","crtloc_lat":"47.678238","crtloc_lng":"-122.131416"
}]
}
This is not corresponding to your sample code. Remove the
connected{ }
wrapping or return correct json for a connected object (whatever the connect is). If you remove the wrapping it should work as #Dietz posted.
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