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;
}
Related
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);
}
i have an application that has to deserialize an array of data wrapped in a "results" Root Object, using Netwonsoft.Json package from NuGet
The Json string is exactly this:
{"results":[{"Coin":"SBD","LP":0.000269,"PBV":-54.36,"MACD1M":true,"MACD30M":true,"MACD1H":true,"MACD1D":true},{"Coin":"XMR","LP":0.027135,"PBV":11.44,"MACD1M":true,"MACD30M":true,"MACD1H":true,"MACD1D":true}]}
This Json string is created from a Console App i made, i wanted it to look like this https://bittrex.com/Api/v2.0/pub/market/GetTicks?marketName=BTC-NEO&tickInterval=hour
My class looks like this
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WindowsFormsApp2
{
public class Result
{
public string Coins { get; set; }
public decimal LastPrice { get; set; }
public decimal PercentBuyVolume { get; set; }
}
public class RootObject
{
public List<Result> results { get; set; }
}
}
In the Main form i have a function to download from a URL that Json (i have XAMPP running Apache) and deserialize it in an array. And it looks like this:
private void DownloadBittrexData()
{
int PanelID = 0;
var Coin = new List<string>();
var LastPrice = new List<decimal>();
var PercentBuyVolume = new List<decimal>();
var MACD1M = new List<bool>();
var MACD30M = new List<bool>();
var MACD1H = new List<bool>();
var MACD1D = new List<bool>();
var client = new WebClient();
var URL = client.DownloadString("http://localhost/test.json");
Console.WriteLine("Json String from URL: " + URL);
var dataDeserialized = JsonConvert.DeserializeObject<RootObject>(URL);
foreach (var data in dataDeserialized.results)
{
Coin.Add(data.Coins);
LastPrice.Add(data.LastPrice);
PercentBuyVolume.Add(data.PercentBuyVolume);
}
int sizeOfArrayClose = Coin.Count - 1;
for (int i = 0; i <= sizeOfArrayClose; i++)
{
Console.WriteLine("Coin: " + Coin[i]);
Console.WriteLine("Lastprice: " + LastPrice[i]);
Console.WriteLine("PBV: " + PercentBuyVolume[i]);
}
}
Newtonsoft.Json is of course declared at the beginning of the form together with System.Net
using System.Net;
using Newtonsoft.Json;
The output looks like this:
Json String from URL: {"results":[{"Coin":"SBD","LP":0.000269,"PBV":-54.36,"MACD1M":true,"MACD30M":true,"MACD1H":true,"MACD1D":true},{"Coin":"XMR","LP":0.027135,"PBV":11.44,"MACD1M":true,"MACD30M":true,"MACD1H":true,"MACD1D":true}]}
Coin:
Lastprice: 0
PBV: 0
Coin:
Lastprice: 0
PBV: 0
It's like it fails to deserialize it after downloading it.
What should i do? Thank you very much.
Your property names don't map to the field names in the JSON. You could rename your C# properties to match the JSON, but it would make for unreadable downstream code.
Instead, you should map your properties (with nice, readable names) to the names that appear in the JSON, using JsonPropertyAttribute:
public class Result
{
public string Coin { get; set; } //didn't bother here: changed property name to Coin
[JsonProperty("LP")]
public decimal LastPrice { get; set; }
[JsonProperty("PBV")]
public decimal PercentBuyVolume { get; set; }
}
your model should be like this for deserialize json
public class Result
{
public string Coin { get; set; }
public double LP { get; set; }
public double PBV { get; set; }
public bool MACD1M { get; set; }
public bool MACD30M { get; set; }
public bool MACD1H { get; set; }
public bool MACD1D { get; set; }
}
public class RootObject
{
public List<Result> results { get; set; }
}
LastPrice and PercentBuyVolume are not available in your model that's the reason it's getting an error.
I tried your exact code on my system and I was able to retrieve the result as expected. Hope this helps, It's easy to understand.
Here is the main class
static void Main(string[] args)
{
RootObject configfile = LoadJson();
foreach (var tResult in configfile.results)
{
Console.WriteLine("Coin: " + tResult.Coin);
Console.WriteLine("Lastprice: " + tResult.LP);
Console.WriteLine("PBV: " + tResult.PBV);
}
Console.ReadLine();
}
LoadJson Function would be
private static RootObject LoadJson()
{
string json = "{\"results\":[{\"Coin\":\"SBD\",\"LP\":0.000269,\"PBV\":-54.36,\"MACD1M\":true,\"MACD30M\":true,\"MACD1H\":true,\"MACD1D\":true},{\"Coin\":\"XMR\",\"LP\":0.027135,\"PBV\":11.44,\"MACD1M\":true,\"MACD30M\":true,\"MACD1H\":true,\"MACD1D\":true}]}";
RootObject configs = Deserialize<RootObject>(json);
return configs;
}
and Deserialize function would be
private static T Deserialize<T>(string json)
{
T unsecureResult;
string _DateTypeFormat = "yyyy-MM-dd HH:mm:ss";
DataContractJsonSerializerSettings serializerSettings = new DataContractJsonSerializerSettings();
DataContractJsonSerializer serializer;
MemoryStream ms;
unsecureResult = default(T);
serializerSettings.DateTimeFormat = new System.Runtime.Serialization.DateTimeFormat(_DateTypeFormat);
serializer = new DataContractJsonSerializer(typeof(T));
ms = new MemoryStream(Encoding.Unicode.GetBytes(json));
unsecureResult = (T)serializer.ReadObject(ms);
return unsecureResult;
}
and Now your Datamodel would be
public class Result
{
public string Coin { get; set; }
public double LP { get; set; }
public double PBV { get; set; }
public bool MACD1M { get; set; }
public bool MACD30M { get; set; }
public bool MACD1H { get; set; }
public bool MACD1D { get; set; }
}
public class RootObject
{
public List<Result> results { get; set; }
}
For example
[DataContract]
public abstract class BaseClass
{
public abstract string id { get; set; }
}
[DataContract(Name = "class1")]
public class concreteClass1 : BaseClass
{
public concreteClass1() { }
[DataMember]
public override string id { get; set; }
[DataMember]
public string prop1 { get; set; }
[DataMember]
public string prop2 { get; set; }
}
[DataContract(Name = "class2")]
public class concreteClass2 : BaseClass
{
public concreteClass2() { }
[DataMember]
public override string id { get; set; }
[DataMember]
public string prop1 { get; set; }
[DataMember]
public string prop2 { get; set; }
}
When I try to serialize a dictionary containing one of the concrete classes like this
static public void Main(string[] args){
Dictionary<string, BaseClass> items = new Dictionary<string, BaseClass>();
items.Add("1", new concreteClass1() { id = "1", prop1 = "blah1" });
items.Add("11", new concreteClass1() { id = "11", prop1 = "blah11" });
var serializer = new DataContractSerializer(items.GetType());
string xmlString = string.Empty;
using (var sw = new StringWriter())
{
using (var writer = new XmlTextWriter(sw))
{
writer.Formatting = System.Xml.Formatting.Indented;
serializer.WriteObject(writer, items );
writer.Flush();
xmlString = sw.ToString();
}
}
}
I get this error when trying to WriteObject
Type 'ConsoleTest.Program+Base' cannot be serialized. Consider marking
it with the DataContractAttribute attribute, and marking all of its
members you want serialized with the DataMemberAttribute attribute.
If the type is a collection, consider marking it with the
CollectionDataContractAttribute. See the Microsoft .NET Framework
documentation for other supported types.
Is there a way to solve this?
EDIT: I also tried using KnownType on the base class but it didn't work
[DataContract]
[KnownType(typeof(concreteClass1))]
[KnownType(typeof(concreteClass2))]
public abstract class BaseClass
{
public abstract string id { get; set; }
}
try this...
using ....
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization;
using System.Xml;
classes...
[DataContract]
[KnownType(typeof(concreteClass1))]
[KnownType(typeof(concreteClass2))]
public abstract class BaseClass
{
[DataMember]
public abstract string id { get; set; }
}
[DataContract(Name = "class1")]
public class concreteClass1 : BaseClass
{
public concreteClass1() { }
[DataMember]
public override string id { get; set; }
[DataMember]
public string prop1 { get; set; }
[DataMember]
public string prop2 { get; set; }
}
[DataContract(Name = "class2")]
public class concreteClass2 : BaseClass
{
public concreteClass2() { }
[DataMember]
public override string id { get; set; }
[DataMember]
public string prop1 { get; set; }
[DataMember]
public string prop2 { get; set; }
}
code....
static void Main(string[] args)
{
Dictionary<string, BaseClass> items = new Dictionary<string, BaseClass>();
items.Add("1", new concreteClass1() { id = "1", prop1 = "blah1" });
items.Add("11", new concreteClass1() { id = "11", prop1 = "blah11" });
// this should work too....
items.Add("999", new concreteClass2() { id = "999", prop1 = "blah999" });
items.Add("888", new concreteClass2() { id = "888", prop1 = "blah888" });
//Serialize(items);
var serializer = new DataContractSerializer(items.GetType());
string xmlString = string.Empty;
try
{
using (var sw = new StringWriter())
{
using (var writer = new XmlTextWriter(sw))
{
writer.Formatting = System.Xml.Formatting.Indented;
serializer.WriteObject(writer, items);
writer.Flush();
xmlString = sw.ToString();
}
}
}
catch (Exception)
{
throw;
}
}
/////////////////////
UPDATE
/////////////////////
As a bit of a bonus (don't feel I eared my 25 points yet) here are two functions that will serialise and deserialise a generic object.....
public static void Serialize<T>(T data)
{
try // try to serialize the collection to a file
{
using (Stream stream = File.Open("data.xml", FileMode.Create))
{
// create DataContractSerializer
DataContractSerializer serializer = new DataContractSerializer(typeof (T));
// serialize the collection (EmployeeList1) to file (stream)
serializer.WriteObject(stream, data);
}
}
catch (IOException)
{
}
}
public static T Deserialize<T>() where T : new()
{
// Create an instance of T
T ReturnListOfT = CreateInstance<T>();
// Try to Deserialize from file stream
try
{
using (Stream stream = File.Open("data.xml", FileMode.Open))
{
// create DataContractSerializer
DataContractSerializer serializer = new DataContractSerializer(typeof (T));
// deserialize the collection (Employee) from file (stream)
ReturnListOfT = (T)serializer.ReadObject(stream);
}
}
catch (IOException)
{
}
return (T)ReturnListOfT;
}
// function to create instance of T
public static T CreateInstance<T>() where T : new()
{
return (T)Activator.CreateInstance(typeof(T));
}
instead of having to modify the XML manually, you could deserialise the object (from a file, in the example 'data.xml') using your existing classes and create a User Interface to allow the user to modify the properties of the object\classes, then re-save\ serialise the modified object back to a file.....
Is it possible to deserialize part of a binary file?
Basically I have an object similar to below, which I serialize into a binary file.
public class MyObject
{
public string Name { get; set; }
public int Value { get; set; }
public IList<MyOtherObject> { get; set; } // lots of data in here (order of kB-MB)
}
What I would like is to be able to deserialize only Name and Value by way of populating a ListView for file selection purposes and then deserialize the rest of the file when needed (i.e. the user chooses that file from the ListView).
As always, any help greatly appreciated and if any 3rd party libraries are suggested they would need to be able to be used freely in a commercial environment.
protobuf-net can do that, because it is not tied to the specific type; for example:
using ProtoBuf;
using System.Collections.Generic;
using System.IO;
[ProtoContract]
public class MyOtherObject { }
[ProtoContract]
public class MyObject
{
[ProtoMember(1)]
public string Name { get; set; }
[ProtoMember(2)]
public int Value { get; set; }
[ProtoMember(3)]
public IList<MyOtherObject> Items { get; set; }
}
[ProtoContract]
public class MyObjectLite
{
[ProtoMember(1)]
public string Name { get; set; }
[ProtoMember(2)]
public int Value { get; set; }
}
static class Program
{
static void Main()
{
var obj = new MyObject
{
Name = "abc",
Value = 123,
Items = new List<MyOtherObject>
{
new MyOtherObject(),
new MyOtherObject(),
new MyOtherObject(),
new MyOtherObject(),
}
};
using (var file = File.Create("foo.bin"))
{
Serializer.Serialize(file, obj);
}
MyObjectLite lite;
using (var file = File.OpenRead("foo.bin"))
{
lite= Serializer.Deserialize<MyObjectLite>(file);
}
}
}
But if you don't want two different types, and/or you don't want to have to add attributes - that can be done too:
using ProtoBuf.Meta;
using System.Collections.Generic;
using System.IO;
public class MyOtherObject { }
public class MyObject
{
public string Name { get; set; }
public int Value { get; set; }
public IList<MyOtherObject> Items { get; set; }
}
static class Program
{
static readonly RuntimeTypeModel fatModel, liteModel;
static Program()
{
// configure models
fatModel = TypeModel.Create();
fatModel.Add(typeof(MyOtherObject), false);
fatModel.Add(typeof(MyObject), false).Add("Name", "Value", "Items");
liteModel = TypeModel.Create();
liteModel.Add(typeof(MyOtherObject), false);
liteModel.Add(typeof(MyObject), false).Add("Name", "Value");
}
static void Main()
{
var obj = new MyObject
{
Name = "abc",
Value = 123,
Items = new List<MyOtherObject>
{
new MyOtherObject(),
new MyOtherObject(),
new MyOtherObject(),
new MyOtherObject(),
}
};
using (var file = File.Create("foo.bin"))
{
fatModel.Serialize(file, obj);
}
MyObject lite;
using (var file = File.OpenRead("foo.bin"))
{
lite = (MyObject)liteModel.Deserialize(
file, null, typeof(MyObject));
}
}
}
How about putting the Name and Valueinto a superclass and serializing them separately?
Alternatively, you could maintain a Dictionary and serialize that into one file.
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 + ')');