Convert JSON object to a list of objects C# - c#

I have a web api service that converts JSON object to a specific list:
here is the model class:
public class rest_all_data
{
public string RestaurantName { get; set; }
public string CategoryName { get; set; }
public string FourSquareID { get; set; }
}
public class rest_collection
{
public List<rest_all_data> rest_all_data { get; set; }
}
and here is the service:
public void AddRestaurantMultiple([FromBody] JObject rest_all)
{
string k = rest_all.ToString();
rest_collection result = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize<rest_collection>(k);
}
and here is the json object:
"restaurants" : [{"RestaurantName":"a","CategoryName":"b","FourSquareID":"c"},{"RestaurantName":"d","CategoryName":"e","FourSquareID":"f"}]
the rest_all object always comes with data and the k string is also a success but the result variable is always null...

try it i have made few changes in your code
public class rest_collection
{
public IEnumerable<rest_all_data> rest_all_datas { get; set; }
}
public void AddRestaurantMultiple([FromBody] JObject rest_all)
{
string k = rest_all.ToString();
JavaScriptSerializer serializer = new JavaScriptSerializer();
rest_collection collection = serializer.Deserialize<rest_collection>(k);
}

try:
public void AddRestaurantMultiple([FromBody] string rest_all)
{
var obj = JsonConvert.DeserializeObject<rest_collection>(rest_all);
}

Related

How can I Deserialize this json? It is giving all null value with following codes

{
"Global Quote": {
"01. symbol": "MSFT",
"02. latest trading day": "2018-11-19",
"03. previous close": "108.2900"}
}
This is the code I m using:
using (var reader = new StreamReader(response.GetResponseStream()))
{
JavaScriptSerializer js = new JavaScriptSerializer();
var objText = reader.ReadToEnd();
//This line is not working.
Stock stock = (Stock)js.Deserialize(objText, typeof(Stock));
return Ok(stock);
}
The stock is model as shown below:
public class Stock
{
public string symbol { get; set; }
public string latesttradingday { get; set; }
public string previousclose { get; set; }
}
All I m getting is Null in all field of Stock. What I m missing here? I m new to JSON.
Use JsonProperty
public class GlobalQuote
{
[JsonProperty("Global Quote")]
public Stock Stock { get; set; }
}
public class Stock
{
[JsonProperty("01. symbol")]
public string symbol { get; set; }
[JsonProperty("02. latest trading day")]
public string latesttradingday { get; set; }
[JsonProperty("03. previous close")]
public string previousclose { get; set; }
}
private static async Task Main(string[] args)
{
string test = #"{
""Global Quote"": {
""01. symbol"": ""MSFT"",
""02. latest trading day"": ""2018-11-19"",
""03. previous close"": ""108.2900""}
}";
var result = JsonConvert.DeserializeObject<GlobalQuote>(test);
}
Full Demo Here
Additional Resources
JsonProperty Class
Maps a JSON property to a .NET member or constructor parameter.

C# receiving json string but unable to deserialize it

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; }
}

c# Newtonsoft deserialize a json string in al list of Objects

i have the following class
using System;
public class AppEventsClass
{
public string title { get; set; }
public string description { get; set; }
}
after calling a remote webservice i retrive the following json string:
{"d":"[title\":\"test\",\"description\":\"test desc\"},{\"title\":\"test2\",\"description\":\"desc test 2\"}]"}
after retriving that json string, how can i convert the string in a List<> of AppEventsClass with Newtonsoft?
I tried several solutions, but nothing that works fine for me.
for example this:
List<AppEventsClass> result = new List<AppEventsClass>();
result = JsonConvert.DeserializeObject<List<AppEventsClass>>(content).ToList();
and this is the .asmx that serializes the string:
[ScriptMethod(UseHttpGet = true)]
public string GetEvents()
{
using (mySQLDataContext ctx = new secondosensoSQLDataContext())
{
List<eventi> eventiList = ctx.eventi.ToList();
List<AppEventsClass> eventiClassList = new List<AppEventsClass>();
for (int i = 0; i < eventiList.Count; i++)
{
AppEventsClass a = new AppEventsClass();
a.title = eventiList[i].titlolo_evento;
a.description = eventiList[i].descrizione_evento;
eventiClassList.Add(a);
}
var json = JsonConvert.SerializeObject(eventiClassList);
return json;
}
}
1st issues seems that the response we retrieve is not formed correctly
Assumed that the json string is looking like the following:
{"d":[{"title":"test","description":"test desc"},{"title":"test2","description":"desc test 2"}]}
The correct class for deserialization should look like this
public class Rootobject
{
public D[] d { get; set; }
}
public class D
{
public string title { get; set; }
public string description { get; set; }
}
Thanks
PS. Here is a working example:
class Program
{
static void Main(string[] args)
{
string json = "{\"d\":[{title:\"test\",description:\"test desc\"},{title:\"test2\",description:\"desc test 2\"}]}";
var result = Newtonsoft.Json.JsonConvert.DeserializeObject<Rootobject>(json);
}
}
public class Rootobject
{
public D[] d { get; set; }
}
public class D
{
public string title { get; set; }
public string description { get; set; }
}

XML to custom Object

I have one xml file and I want to generate custom list from that xml using Linq.
here is my code. But I am not getting any records.Here is my code.
public class TemplateSettings {
public string DecimalSeparator { get; set; }
public string ThousandSeparator { get; set; }
public string DateSeparator { get; set; }
public string TimeSeparator { get; set; }
}
XML Here
<TemplateSetting>
<DecimalSeparator>1</DecimalSeparator>
<ThousandSeparator>2</ThousandSeparator>
<DateSeparator>3</DateSeparator>
<TimeSeparator>4</TimeSeparator>
<DateFormat>dd/MM/yyyy</DateFormat>
<ValueDelimiter>tr</ValueDelimiter>
<QuoteCharacter>r</QuoteCharacter>
<IsHeader>False</IsHeader>
</TemplateSetting>
And my code to get object from xml is
var a = (from x in objTemplateMasterEAL.TemplatSettingsXML.Elements("TemplateSetting")
select new TemplateSettings()
{
DateFormat = (string)x.Element("DateFormat"),
DecimalSeparator = (string)x.Element("DecimalSeparator"),
ThousandSeparator = (string)x.Element("ThousandSeparator"),
DateSeparator = (string)x.Element("DateSeparator"),
TimeSeparator = (string)x.Element("TimeSeparator"),
QuoteCharacter = (string)x.Element("QuoteCharacter"),
ValueDelimiter = (string)x.Element("ValueDelimiter"),
IsHeaderLine = (bool)x.Element("IsHeader")
}).ToList<TemplateSettings>();
Can any one suggest me what is wrong here ?
If your goal is just to deserialize the XML to object you can simply use this:
class Program
{
static void Main(string[] args)
{
using (StreamReader reader = new StreamReader("Sample.xml"))
{
var serializer = new XmlSerializer(typeof(TemplateSetting));
var templateSetting = (TemplateSetting)serializer.Deserialize(reader);
}
}
}
[XmlRoot]
public class TemplateSetting
{
public string DecimalSeparator { get; set; }
public string ThousandSeparator { get; set; }
public string DateSeparator { get; set; }
public string TimeSeparator { get; set; }
}
I make only on one change and its working fine for me.
<TemplateSettings>
<TemplateSetting>
<DecimalSeparator>1</DecimalSeparator>
<ThousandSeparator>2</ThousandSeparator>
<DateSeparator>3</DateSeparator>
<TimeSeparator>4</TimeSeparator>
<DateFormat>dd/MM/yyyy</DateFormat>
<ValueDelimiter>tr</ValueDelimiter>
<QuoteCharacter>r</QuoteCharacter>
<IsHeader>False</IsHeader>
</TemplateSetting>
</TemplateSettings>

How to populate a Generic List from a JSON string using C#.NET?

I am trying to populate a List in C# but the values are not appearing in the array - though it does not throw an error until I try and set a variable with an array index (because it is out of range of course).
This is the exact return string strJSON I am seeing while debugging.
strJSON "{\"id\":34379899,\"name\":\"Revelation22\",\"profileIconId\":547,\"summonerLevel\":30,\"revisionDate\":1387913628000}"
Why is the List (array) not populating?
This is the code for KeyValue.cs (which to be honest I do not know yet why it needs another class)
namespace LoLSummoner
{
public class KeyValue
{
public int id {get; set;}
public string name {get; set;}
public int profileIconId {get; set;}
public int summonerLevel {get; set;}
public int revisionDate {get; set;}
}
}
And this is the code from Summoner.svc.cs
namespace LoLSummoner
{
public class Summoner : ISummoner
{
public int GetSummonerID(string SummonerName)
{
int summonerId = 0;
WebClient client = new WebClient();
string strJSON = client.DownloadString("http://prod.api.pvp.net/api/lol/na/v1.2/summoner/by-name/" + SummonerName + "?api_key=xxxx");
JavaScriptSerializer js = new JavaScriptSerializer();
KeyValue[] arrJSON = js.Deserialize<List<KeyValue>>(strJSON).ToArray();
summonerId = Convert.ToInt32(arrJSON.GetValue(0));
return summonerId;
}
}
}
Your JSON contains a single object, not an array.
Therefore, you can only deserialize it as KeyValue.
Your RevisionDate property has to be long, because 1387913628000, and that's the value your trying to deserialize, exceeds int range.
Your JSON contains information about only one KeyValue object, not an array of there, so you have to deserialize it as KeyValue, no KeyValue[]:
KeyValue item = js.Deserialize<KeyValue>(strJSON);
Having KeyValue instance you can use standard property syntax to return ID:
return item.id;
I find this code working:
public class KeyValue
{
public int id { get; set; }
public string name { get; set; }
public int profileIconId { get; set; }
public int summonerLevel { get; set; }
public long revisionDate { get; set; }
}
static void Main(string[] args)
{
var input = #"{""id"":34379899,""name"":""Revelation22"",""profileIconId"":547,""summonerLevel"":30,""revisionDate"":1387913628000}";
JavaScriptSerializer js = new JavaScriptSerializer();
var item = js.Deserialize<KeyValue>(input);
var summonerId = item.id;
}
I do not know yet why it needs another class
You don't need that class. It think the simplest way would be to deserialize your json directly to Dictionary<string, object>
var strJSON = "{\"id\":34379899,\"name\":\"Revelation22\",\"profileIconId\":547,\"summonerLevel\":30,\"revisionDate\":1387913628000}";
var dict = new JavaScriptSerializer()
.Deserialize<Dictionary<string, object>>(strJSON);
Console.WriteLine(dict["name"]);
Console.WriteLine(ToDateTime((long)dict["revisionDate"]));
DateTime ToDateTime(long l)
{
return new DateTime(1970, 1, 1).AddMilliseconds(l);
}
As already noted, the revisionDate will cause a runtime binding exception if it is not typed as a long.
public class KeyValue
{
public int id { get; set; }
public string name { get; set; }
public int profileIconId { get; set; }
public int summonerLevel { get; set; }
public long revisionDate { get; set; }
}
In addition to that, you may wish to attempt a simple detection in order to deserialize this as either an object or an array of objects (if in the future the name is no longer unique).
public int GetSummonerID(string SummonerName)
{
int summonerId = 0;
WebClient client = new WebClient();
string strJSON = client.DownloadString("http://prod.api.pvp.net/api/lol/na/v1.2/summoner/by-name/" + SummonerName + "?api_key=xxxx");
JavaScriptSerializer js = new JavaScriptSerializer();
if(strJSON[0] == '[')
{
return js.Deserialize<KeyValue[]>(strJSON)[0].id;
}
else
{
return js.Deserialize<KeyValue>(strJSON).id;
}
return summonerId;
}
One thing to note is that your JSON string contains only a single KeyValue, not a list of them. Another problem is that the revision date is too large to fit in a 32 bit int, so consider using a long instead.
Here's some example code that reads your sample string and prints out some of the values.
public class KeyValue
{
public int id { get; set; }
public string name { get; set; }
public int profileIconId { get; set; }
public int summonerLevel { get; set; }
public long revisionDate { get; set; }
}
static void Main(string[] args)
{
var strJSON = "{\"id\":34379899,\"name\":\"Revelation22\",\"profileIconId\":547,\"summonerLevel\":30,\"revisionDate\":1387913628000}";
var serializer = new JavaScriptSerializer();
var keyValue = serializer.Deserialize<KeyValue>(strJSON);
var id = keyValue.id;
var name = keyValue.name;
var level = keyValue.summonerLevel;
Console.WriteLine("Summoner name:{0}, Id:{1}, Level:{2}", name, id, level);
Console.Read();
}

Categories

Resources