Json Deserialization to a class - c#

I have dynamic json result and i want to create an object for that json string. After that i will fill that object with the deserialized object. Here is the json string:
[{"_34":{
"Id":"34",
"Z":["42b23718-bbb8-416e-9241-538ff54c28c9","c25ef97a-89a5-4ed7-89c7-9c6a17c2413b"],
"C":[]
}
}]
How does the object look like? Or how can i deserialize this string to a class.
Thanks.

You can use the JavaScriptSerializer which available out of the box or json.net if you prefer something open source.
Based on Darin Dimitrov's sample, here's how you'd do with json.net:
using System.Collections.Generic;
using System;
using Newtonsoft.Json;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string json = "[{\"_34\":{ \"Id\":\"34\", \"Z\":[\"42b23718-bbb8-416e-9241-538ff54c28c9\",\"c25ef97a-89a5-4ed7-89c7-9c6a17c2413b\"], \"C\":[] } }]";
var result = JsonConvert.DeserializeObject<Dictionary<string, Result>[]>(json);
Console.WriteLine(result[0]["_34"].Z[1]);
}
}
public class Result
{
public string Id { get; set; }
public string[] Z { get; set; }
public string[] C { get; set; }
}
}

Here's an example:
using System;
using System.Collections.Generic;
using System.IO;
using System.Web.Script.Serialization;
public class Result
{
public string Id { get; set; }
public string[] Z { get; set; }
public string[] C { get; set; }
}
class Program
{
static void Main()
{
var json = #"[{""_34"": {""Id"": ""34"",""Z"": [""42b23718-bbb8-416e-9241-538ff54c28c9"",""c25ef97a-89a5-4ed7-89c7-9c6a17c2413b""],""C"": []}}]";
var serializer = new JavaScriptSerializer();
var result = serializer.Deserialize<Dictionary<string, Result>[]>(json);
Console.WriteLine(result[0]["_34"].Z[1]);
}
}

Target class
public class Target
{
public string Id;
public List<string> Z;
public List<string> C;
}
Deserialization
var ser = new JavaScriptSerializer();
var obj = ser.Deserialize<Target>(json);

Wrap your string in eval function:
var myObject = eval('(' + myJSONtext + ')');

Related

How do I call JSON in a simplified manner

I am connecting to an external API which seems to be returning JSON
using (var client = new APIClient())
{
var data = client.General.GetAccountInfo().Data.Balances;
}
When I move over .Data.Balances, it shows:
IEnumerable<API.Net.Objects.Spot.SpotData.APIBalance>
API.Net.Objects.Spot.SpotData.APIAccountInfo.Balances { get; set; }
List of assets and their current balances
Here is an extract of the JSON data:
"balances":[
{
"asset":"ABC",
"free":"0.00000000",
"locked":"0.00000000"
},
{
"asset":"DEF",
"free":"0.00000000",
"locked":"0.00000000"
},
{
"asset":"GHI",
"free":"0.00000000",
"locked":"0.00000000"
}
]
How do I make use of this data so if I type console.writeline(data[0]["asset"]), it gives me ABC?
This seems to be the simplist solution:
using System.Linq;
using (var client = new APIClient())
{
var data = client.General.GetAccountInfo().Data.Balances.ToList();
Console.WriteLine(data[0].asset);
Console.WriteLine(data[0].free);
Console.WriteLine(data[0].locked);
}
Hy,
From the sample file you can create a class ´balance »
Public class balance
{
Public string asset {get; set;}
Public Free .......
Public Locked .....
}
And then you can use Json.net
To deserialize the JSon file
public void serializejson()
{
List balances = JsonConvert.DeserializeObject<List>(data);
}
}
using System;
using System.Collections.Generic;
using System.IO;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace Game
{
public class Balance
{
[JsonPropertyName("asset")]
public string Asset { get; set; }
[JsonPropertyName("free")]
public string Free { get; set; }
[JsonPropertyName("locked")]
public string Locked { get; set; }
}
public class Root
{
[JsonPropertyName("balances")]
public List<Balance> Balances { get; set; }
}
class Program
{
static void Main(string[] args)
{
var data = File.ReadAllText("test.json");
var deserialized = JsonSerializer.Deserialize<Root>(data);
var balances = deserialized.Balances;
// Don't iterati in such a way! Use foreach instead.
for (int i = 0; i < balances.Count; i++)
{
Console.WriteLine($"{balances[i].Asset} {balances[i].Free} {balances[i].Locked}");
}
foreach (var balance in balances)
{
Console.WriteLine($"{balance.Asset} {balance.Free} {balance.Locked}");
}
}
}
}
You can use this code for you:
public class Balance {
public string asset { get; set; }
public string free { get; set; }
public string locked { get; set; }
}
public class Root {
public List<Balance> balances { get; set; }
}
And for deserialize:
using (var client = new APIClient())
{
var data = client.General.GetAccountInfo().Data.Balances;
Root myDeserializedClass = JsonConvert.DeserializeObject<Root>(data);
Console.WriteLine(myDeserializedClass.balances[0].asset);
}

Getting parts of a repetitive string in C#

Extracting parts of a string is a common question, but here the string content, e.g. ' "main\":{\"temp\": ' is repetitive:
string test = "{\"cod\":\"200\",\"message\":0,\"cnt\":40,\"list\":[{\"dt\":1576810800,\"main\":{\"temp\":288.19,\"feels_like\":284.44,\"temp_min\":288.19,\"temp_max\":291.53,\"{\"dt\":1576821600,\"main\":{ \"temp\":283.97,\"feels_like\":281.56,\"temp_min\":283.97,\"temp_max\":286.47,\"pressure\":1007,\"sea_level\":1007,\"grnd_level\":997,\"humidity\":93,\"temp_kf\":-2.5},\"weather\":[{\"id\":501,\"main\":\"Rain\",\"description\":\"moderate rai\",\"icon\":\"10d\"}],\"clouds\":{\"all\":90},\"wind\"";
Using
string s = test.Substring(test.IndexOf("\"main\":{\"temp\":") + 15);
I get
288.19,"feels_like":284.44,,"temp_min":288.19,"temp_max":291.53,"{"dt":157682160
0,"main":{ "temp":283.97,"feels_like":281.56,"temp_min":283.97,"temp_max":286.47
,"pressure":1007,"sea_level":1007,"grnd_level":997,"humidity":93,"temp_kf":-2.5}
,"weather":[{"id":501,"main":"Rain","description":"moderate rain","icon":"10d"}],
"clouds":{"all":90},"wind"
instead of
288.19
Any clue what command would help? Should be something that can be adapted to ' "temp_max" ' or ' "pressure" '.
Cheers
Thanks to Mohammed, here's the working code spitting out all tempeatures:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using Newtonsoft.Json;
namespace ConsoleApp2
{
public class RootObject
{
public List<MyList> list { get; set; }
}
public class MyList
{
public Main main { get; set; }
}
public class Main
{
public double temp { get; set; }
}
class Program
{
static void Main()
{
using (WebClient client = new WebClient())
{
Console.WriteLine("ACCESSING ...");
string test = client.DownloadString("http://api.openweathermap.org/data/2.5/forecast?q=Auckland,NZ&APPID=45c3e583468bf450fc17026d6734507e");
//string test = "{\"cod\":\"200\",\"message\":0,\"cnt\":40,\"list\":[{\"dt\":1576810800,\"main\":{\"temp\":288.19,\"feels_like\":284.44,\"temp_min\":288.19,\"temp_max\":291.53,\"{\"dt\":1576821600,\"main\":{ \"temp\":283.97,\"feels_like\":281.56,\"temp_min\":283.97,\"temp_max\":286.47,\"pressure\":1007,\"sea_level\":1007,\"grnd_level\":997,\"humidity\":93,\"temp_kf\":-2.5},\"weather\":[{\"id\":501,\"main\":\"Rain\",\"description\":\"moderate rai\",\"icon\":\"10d\"}],\"clouds\":{\"all\":90},\"wind\"";
var myobject = JsonConvert.DeserializeObject<RootObject>(test); //test is JSON response as string
foreach (var item in myobject.list)
{
var temp = item.main.temp;
Console.WriteLine(temp);
}
Console.ReadLine();
}
}
}
}
Using
var regexGroups = Regex.Matches(test, "\"main\" ?: ?{ ?\"temp\" ?: ?(\\d+\\.\\d+)")
.Select(x => x.Groups[1].Value);
You can get all \"main\":{\"temp\": values.
//classes.cs
public class RootObject
{
public List<MyList> list { get; set; }
}
public class MyList
{
public Main main { get; set; }
}
public class Main
{
public double temp { get; set; }
}
//API client
using Newtonsoft.Json;
var myobject = JsonConvert.DeserializeObject<RootObject>(test); //test is JSON response as string
foreach(var item in myobject.list){
var temp = item.main.temp;
}
//Hope it helps

C# Json and HttpWebRequest

I used HttpWebRequest to get the content from a website.
The problem is that I got a response in json and I don't really know how to use, convert and implement that data in my program.
Current code:
namespace Web_Scraper
{
class Program
{
static void Main(string[] args)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://steamcommunity.com/market/priceoverview/?currency=3&appid=440&market_hash_name=Genuine%20Purity%20Fist");
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader stream = new StreamReader(response.GetResponseStream());
string final_response = stream.ReadToEnd();
Console.WriteLine("Genuine Purity Fist");
Console.WriteLine(final_response);
Console.ReadKey();
}
}
}
Response:
{"success":true,"lowest_price":"1,05\u20ac","volume":"26","median_price":"1,06\u20ac"}
json2csharp code:
public class RootObject
{
public bool success { get; set; }
public string lowest_price { get; set; }
public string volume { get; set; }
public string median_price { get; set; }
}
Hey you could downloade Json.NET and parse your json string like this:
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://steamcommunity.com/market/priceoverview/?currency=3&appid=440&market_hash_name=Genuine%20Purity%20Fist");
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader stream = new StreamReader(response.GetResponseStream());
var final_response = stream.ReadToEnd();
// Converts the unicode to string correctValue.
string correctValue = "Euro";
StringBuilder sb = new StringBuilder(final_response);
if (sb.ToString().Contains("\\u20ac"))
{
sb.Replace("\\u20ac", correctValue);
}
dynamic items = JObject.Parse(sb.ToString());
bool success = items.success;
string lowest = items.lowest_price;
string volume = items.volume;
string median = items.median_price;
// Create a test object of RootObject class and display it's values in cw.
RootObject r = new RootObject(success, lowest, volume, median);
Console.WriteLine("TEST OBJECT VALUES: Success: " + r.success + ", lPrice: " + r.lowest_price + ", vol: " + r.volume + ", mPrice: " + r.median_price + "\n");
// Calculation example
double num1 = Convert.ToDouble(r.FixComma(r.lowest_price,correctValue));
double num2 = Convert.ToDouble(r.FixComma(r.median_price, correctValue));
double result = num1 + num2;
Console.WriteLine("Result: " + result+"\n");
Console.WriteLine("Genuine Purity Fist");
Console.WriteLine(final_response);
Console.ReadKey();
}
}
public class RootObject
{
public bool success { get; set; }
public string lowest_price { get; set; }
public string volume { get; set; }
public string median_price { get; set; }
public RootObject(bool success, string lowest_price, string volume, string median_price)
{
this.success = success;
this.lowest_price = lowest_price;
this.volume = volume;
this.median_price = median_price;
}
public string FixComma(string value,string currency)
{
string correctValue = ".";
string correctValue2 = "";
StringBuilder sb = new StringBuilder(value);
if (sb.ToString().Contains(","))
{
sb.Replace(",", correctValue);
}
if (sb.ToString().Contains(currency))
{
sb.Replace(currency, correctValue2);
}
return sb.ToString();
}
}
}
Here is a link that explains how to downloade Json.NET https://www.nuget.org/packages/newtonsoft.json/.
One option is to use the JavaScriptSerializer class in the System.Web.Script.Serialization namespace.
For example:
RootObject obj = new JavaScriptSerializer().Deserialize<RootObject>(final_response);
Other options might be:
Do it yourself using reflection or manual parsing.
Third-party libraries like this one.
I would use JSON.NET for this. It provides a powerful and flexible way to deserialize and consume the data (and lets you change your mind about how to do it fairly easily later). It's also available as a NuGet package.
The simplest way would be to deserialize it into a dynamic or Object instance:
var object = JsonConvert.Deserialize<Object>(final_response);
var isSuccessful = object.success; // true or false
// ...
(You can replace object with dynamic too.)
If you want to deserialize to a class, create one:
class PriceData {
public bool success { get; set; }
public string lowest_price { get; set; }
public string volume { get; set; }
public string median_price { get; set; }
}
Then call .Deserialize<PriceData>(final_response) instead.
If you don't like lowercase-named or underscore-named variables (which is not the common style in C#), you can override the deserialization to specify which field to use for which C# property:
class PriceData {
[JsonProperty("success")]
public bool Success { get; set; }
[JsonProperty("lowest_price")]
public string LowestPrice { get; set; }
[JsonProperty("volume")]
public string Volume { get; set; }
[JsonProperty("median_price")]
public string MedianPrice { get; set; }
}

Read a JSON object

I'm trying to read a JSON object using JavaScriptSerializer. Currently i'm unable to read the JSON object with my code.
below is my JSON object.
{"data":[{"id":17,"name":"RedBug Project","can_modify":true,"description":"","start_date":"1899-01-01T00:00:00Z","due_date":"1899-01-01T00:00:00Z","is_active":true,"parent":{"id":0}},{"id":14,"name":"RedRock","can_modify":true,"description":"","start_date":"1899-01-01T00:00:00Z","due_date":"1899-01-01T00:00:00Z","is_active":true,"parent":{"id":0},"children":[{"id":16,"name":"WEB","can_modify":true,"description":"","start_date":"1899-01-01T00:00:00Z","due_date":"1899-01-01T00:00:00Z","is_active":true,"parent":{"id":14}}]}]}
Method to Read JSON
public Dictionary<string, string> ReadJSONProject(string jsObject)
{
var json = jsObject;
JavaScriptSerializer serializer = new JavaScriptSerializer();
dynamic jsonObject = serializer.Deserialize<dynamic>(json);
Dictionary<string, string> dic = new Dictionary<string, string>();
foreach (var item in jsonObject)
{
var a = item;
dic.Add(item["id"], item["name"]);
}
return dic;
}
I need to read the below values to the dictionary
"id":17,"name":"RedBug Project"
"id":14,"name":"RedRock"
namespace WebApplication2
{
public partial class WebForm3 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string s = #"{""data"":[{""id"":17,""name"":""RedBug Project"",""can_modify"":true,""description"":"""",""start_date"":""1899-01-01T00:00:00Z"",""due_date"":""1899-01-01T00:00:00Z"",""is_active"":true,""parent"":{""id"":0}},{""id"":14,""name"":""RedRock"",""can_modify"":true,""description"":"""",""start_date"":""1899-01-01T00:00:00Z"",""due_date"":""1899-01-01T00:00:00Z"",""is_active"":true,""parent"":{""id"":0},""children"":[{""id"":16,""name"":""WEB"",""can_modify"":true,""description"":"""",""start_date"":""1899-01-01T00:00:00Z"",""due_date"":""1899-01-01T00:00:00Z"",""is_active"":true,""parent"":{""id"":14}}]}]}";
ReadJSONProject(s);
}
protected Dictionary<string, string> ReadJSONProject(string jsObject)
{
var json = jsObject;
JavaScriptSerializer serializer = new JavaScriptSerializer();
dynamic jsonObject = serializer.Deserialize<dynamic>(json);
Dictionary<string, string> dic = new Dictionary<string, string>();
var data = jsonObject["data"];
foreach (var record in data)
{
var id = ((int)record["id"]).ToString();
var name = record["name"] as string;
dic.Add(id, name);
}
return dic;
}
}
}
Refer below example and modify according to your need.
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Objects;
using System.Data.SqlClient;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Runtime.Serialization.Json;
using System.Threading;
using System.Xml;
using ConsoleDemo.Controller;
using ConsoleDemo.Model;
using Microsoft.Practices.Unity;
namespace ConsoleDemo
{
class Program
{
static void Main(string[] args)
{
var data = #"{""Root"": {""data"": [{""CardName"": ""card1"",""functions"": [{""State"": ""OPEN""},{""State"": ""INHERENT""}]},{""CardName"": ""card2"",""functions"": [{""State"": ""CLOSED""},{""State"": ""INHERENT""}]}]}";
RootClass dynObj = JsonHelper.JsonDeserialize<RootClass>(data); //Get the object
Console.ReadKey();
}
}
[DataContract]
public class RootClass
{
[DataMember(Name = "Root")]
public Data Root { get; set; }
}
[DataContract]
public class Data
{
[DataMember(Name = "data")]
public List<Card> data { get; set; }
}
[DataContract]
public class Card
{
[DataMember(Name = "CardName")]
public string CardName { get; set; }
[DataMember(Name = "functions")]
public List<Function> Functions { get; set; }
}
[DataContract]
public class Function
{
[DataMember(Name = "State")]
public string State { get; set; }
}
public class JsonHelper
{
/// <summary>
/// JSON Serialization
/// </summary>
public static string JsonSerializer<T>(T t)
{
var ser = new DataContractJsonSerializer(typeof(T));
var ms = new MemoryStream();
ser.WriteObject(ms, t);
var jsonString = Encoding.UTF8.GetString(ms.ToArray());
ms.Close();
return jsonString;
}
/// <summary>
/// JSON Deserialization
/// </summary>
public static T JsonDeserialize<T>(string jsonString)
{
var ser = new DataContractJsonSerializer(typeof(T));
var ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString));
var obj = (T)ser.ReadObject(ms);
return obj;
}
}
}
In the foreach-loop is retrieving the member "data" which is an array. You need to iterate the elements of this array to access "id" and "name."
Here is my implementation without using dynamics BTW you can use http://json2csharp.com/ to convert complex json to c# classes easily
public class Item
{
public string id { get; set; }
public string name { get; set; }
public bool can_modify { get; set; }
public string description { get; set; }
public string start_date { get; set; }
public string due_date { get; set; }
public bool is_active { get; set; }
public Item parent { get; set; }
public List<Item> children { get; set; }
}
public class RootObject
{
public List<Item> data { get; set; }
}
public Dictionary<string, string> ReadJSONProject(string jsObject)
{
var json = jsObject;
JavaScriptSerializer serializer = new JavaScriptSerializer();
var jsonObject = serializer.Deserialize<RootObject>(json);
Dictionary<string, string> dic = new Dictionary<string, string>();
foreach (var item in jsonObject.data)
{
dic.Add(item.id, item.name);
}
return dic;
}

Discover output class from json.net

I'm doing a project where I dynamically build a set of objects based on reflection and serialize it (using json.net).
What I want to do is to deserialize it and recreate the object tree, but I don't know the final class type.
So how can I find out?
Here's an example:
public class insideBleah
{
public int BProperty
{ get; set; }
}
public class bleah
{
public int AProperty
{ get; set; }
public insideBleah Inside
{ get; set; }
}
and
var bleah = new bleah();
bleah.AProperty = 1;
bleah.Inside = new insideBleah();
bleah.Inside.BProperty = 2;
var output = JsonConvert.SerializeObject(bleah, new JsonSerializerSettings()
{
TypeNameHandling = TypeNameHandling.Objects
});
This produces the output string:
"{\"$type\":\"jsontest.bleah, jsontest\",\"AProperty\":1,\"Inside\":{\"$type\":\"jsontest.insideBleah, jsontest\",\"BProperty\":2}}"
So I can see the class in there. It's so close! But I can't seem to tease the information out.
How can I do this? I can't do:
var newObject = (bleah)JsonConvert.DeserializeObject<bleah>(output);
because I don't know it's a 'bleah'.
How can I handle this?
Thanks in advance
Why can you just use:
using System;
using Newtonsoft.Json;
namespace ConsoleApplication1
{
class Program
{
private static void Main(string[] args)
{
var bleah = new Person();
var settings = new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.Objects };
var output = JsonConvert.SerializeObject(bleah, settings);
Console.WriteLine(output);
var deserializeObject = JsonConvert.DeserializeObject(output, settings);
Console.WriteLine(deserializeObject.GetType().Name);
}
}
class Person
{
public string Name { get; set; }
}
}
The output:
{"$type":"ConsoleApplication1.Person, ConsoleApplication1","Name":null}
Person

Categories

Resources