How to convert Json array to list of objects in c#
MY Json array:
{"allAdultFares":["0-5000.00","1-8000.00"],"Flag":"N"},
Class:
public List<Sellrate> allAdultFares { get; set; }
public class Sellrate
{
public string Singe { get; set; }
public string Double { get; set; }
}
I need O/p:
Singe :5000
Double :8000
Here's some simple code to parse your json without creating a proper class to represent its structure like Jon suggested. I might have misunderstood the exact structure of your json so here is the sample json I worked with, perhaps you will need to make small adjustments to it will fit your case:
{
"rateDetails":[
{
"date":"19-9-2015",
"allAdultFares":["0-5000.00","1-8000.00"],
"Flag":"N"
},
{
"date":"20-9-2015",
"allAdultFares":["0-9000.00","1-9000.00"],
"Flag":"N"
}
]
}
I used JSon.Net to parse the file, you can get it from nuget.
var input = JObject.Parse(File.ReadAllText("sample.json"));
var rateDetails = (JArray)input["rateDetails"];
var a = rateDetails
.Select(t => (JArray)t["allAdultFares"])
.Select(t =>
new Sellrate()
{
Singe = t[0].ToString().Split('-')[1].Replace(#"""", ""),
Double = t[1].ToString().Split('-')[1].Replace(#"""", "")
}).ToList();
i changed & getting o/p
public string[] allAdultFares{ get; set; }
Single: { "field1":"value1","field2":"value2" }
Array: [ { "field1":"value1","field2":"value2" }, { "field1":"value1","field2":"value2" } ]
public class Test
{
public string field1 { get; set; }
public string field2 { get; set; }
}
Test myDeserializedObj = (Test)JavaScriptConvert.DeserializeObject(Request["jsonString"], typeof(Test));
List<test> myDeserializedObjList = (List<test>)Newtonsoft.Json.JsonConvert.DeserializeObject(Request["jsonString"], typeof(List<test>));
Related
I have a list of objects in below json format. I would like to deserialize using below code. It is throwing unable to convert to object error. I have tried below three options, but didnt help. jsoninput is a IEnumerable<string>converted into json object using ToJson().
Error:
{"Error converting value \"{\"id\":\"11ef2c75-9a6d-4cef-8163-94daad4f8397\",\"name\":\"bracing\",\"lastName\":\"male\",\"profilePictureUrl\":null,\"smallUrl\":null,\"thumbnailUrl\":null,\"country\":null,\"isInvalid\":false,\"userType\":0,\"profilePrivacy\":1,\"chatPrivacy\":1,\"callPrivacy\":0}\" to type 'Api.Models.UserInfo'. Path '[0]', line 1, position 271."}
var requests1 = JsonConvert.DeserializeObject<UsersInfo>(jsoninput);
var requests2 = JsonConvert.DeserializeObject<IEnumerable<UserInfo>>(jsoninput);
var requests3 = JsonConvert.DeserializeObject<List<UserInfo>>(jsoninput);
//Below are my classes,
public class UsersInfo
{
public List<UserInfo> UserInfoList { get; set; }
public UsersInfo()
{
UserInfoList = new List<UserInfo>();
}
}
public class UserInfo
{
public string Id { set; get; }
public string Name { set; get; }
public string LastName { set; get; }
public string ProfilePictureUrl { set; get; }
public string SmallUrl { set; get; }
public string ThumbnailUrl { get; set; }
public string Country { set; get; }
public bool IsInvalid { set; get; }
}
Below is my json object,
["{\"id\":\"11ef2c75-9a6d-4cef-8163-94daad4f8397\",\"name\":\"bracing\",\"lastName\":\"male\",\"profilePictureUrl\":null,\"smallUrl\":null,\"thumbnailUrl\":null,\"country\":null,\"isInvalid\":false}","{\"id\":\"318c0885-2720-472c-ba9e-1d1e120bcf65\",\"name\":\"locomotives\",\"lastName\":\"riddles\",\"profilePictureUrl\":null,\"smallUrl\":null,\"thumbnailUrl\":null,\"country\":null,\"isInvalid\":false}"]
Looping through individual items in json input and if i deserialize it like below, it works fine. But i want to deserialize the list fully. Note: jsoninput was a IEnumerable<string> before i convert in json object.
foreach (var re in jsoninput)
{
var request0 = JsonConvert.DeserializeObject<UserInfo>(re);
}
Please look at this fiddle: https://dotnetfiddle.net/XpjuL4
This is the code:
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
//Below are my classes,
public class UsersInfo
{
public List<UserInfo> UserInfoList { get; set; }
public UsersInfo()
{
UserInfoList = new List<UserInfo>();
}
}
public class UserInfo
{
public string Id { set; get; }
public string Name { set; get; }
public string LastName { set; get; }
public string ProfilePictureUrl { set; get; }
public string SmallUrl { set; get; }
public string ThumbnailUrl { get; set; }
public string Country { set; get; }
public bool IsInvalid { set; get; }
}
public class Program
{
public static void Main()
{
Console.WriteLine("Hello World");
Option1();
Option2();
}
public static void Option1(){
string json = #"{""UserInfoList"":[
{""id"":""11ef2c75 - 9a6d - 4cef - 8163 - 94daad4f8397"",""name"":""bracing"",""lastName"":""male"",""profilePictureUrl"":null,""smallUrl"":null,""thumbnailUrl"":null,""country"":null,""isInvalid"":false},
{ ""id"":""318c0885-2720-472c-ba9e-1d1e120bcf65"",""name"":""locomotives"",""lastName"":""riddles"",""profilePictureUrl"":null,""smallUrl"":null,""thumbnailUrl"":null,""country"":null,""isInvalid"":false}
]}";
var obj = JsonConvert.DeserializeObject<UsersInfo>(json);
obj.UserInfoList.ForEach(e => Console.WriteLine(e.Id));
}
public static void Option2(){
string json = #"[
{""id"":""11ef2c75 - 9a6d - 4cef - 8163 - 94daad4f8397"",""name"":""bracing"",""lastName"":""male"",""profilePictureUrl"":null,""smallUrl"":null,""thumbnailUrl"":null,""country"":null,""isInvalid"":false},
{ ""id"":""318c0885-2720-472c-ba9e-1d1e120bcf65"",""name"":""locomotives"",""lastName"":""riddles"",""profilePictureUrl"":null,""smallUrl"":null,""thumbnailUrl"":null,""country"":null,""isInvalid"":false}
]";
var obj = JsonConvert.DeserializeObject<List<UserInfo>>(json);
obj.ForEach(e => Console.WriteLine(e.Id));
}
}
Both work, and are basically very close to what you are doing. You can either serialize it as a list (based on your json, I think that's the closest to your use case, and that's Option 2).
However, put extra attention to the JSON. I had to re-parse your JSON to make it work (https://jsonformatter.org/json-parser is a nice website to do it). For the sake of explaining the example, in C#, # means raw string, and in raw string, quotes are escaped with double quotes "".
I would expect that the business logic generating this JSON is not correct, if the JSON you pasted is the direct result from it.
EDIT
Given the OP's comment:
Thanks Tu.ma for your thoughts. The other method returns
IEnumerable which is nothing but
Dictionary.Where(x => x.Value == null).Select(x =>
x.Key).ToHashSet(). The values in Dictionary are -> Key
is String, Value is UserInfo object serialized. So, in that case i
should deserialize one by one? If not, i should serialize entire list
in one shot? Am i right? – Raj 12 hours ago
The problem is in the way you are generating the list of UsersInfo. The result from Dictionary<string,string>.Where(x => x.Value == null).Select(x =>
x.Key).ToHashSet() is a bunch of strings, not of objects, so you need to serialize them one by one.
If you are worried about the linearity of the approach, you could consider running through it in parallel. Of course, you need to judge if it fits your application.
var userInfoStrings = Dictionary<string,string>.Where(x => x.Value == null).Select(x => x.Key).ToHashSet();
var UserInfoList = userInfoStrings.AsParallel().Select (u => JsonConvert.DeserializeObject<UsersInfo>(u)).ToList();
I am pretty new to coding and here is my requirement:
I am getting a JSON response which has an array of values (refer read,update,delete in the below JSON response)
The number of values is dynamic and tend to vary each time.
I want to know how to retrieve them and put into an string array and return the values
Eg.: end result should be like
string[] deleteValues = {"MCS:Menu:Admin","MCS:test"}
In case if there is answer already available to this question, please point me in the right direction.
Thanks in advance
==========================================
I am able to get the values this way...
string value1 = new JavaScriptSerializer().Deserialize<JSON_Deconstructor>(resp).Permitted[0].Delete[0].ToString();
string value2 = new JavaScriptSerializer().Deserialize<JSON_Deconstructor>(resp).Permitted[0].Delete[1].ToString();
but since the number of values in delete is dynamic, i need to how to pull them.
====================
the code snippet:
string resp = new StreamReader(request1.GetResponse().GetResponseStream()).ReadToEnd(); // resp is a JSON response from a server
JSON_Deconstructor dc = new JSON_Deconstructor { };
dc.Permitted = new Permitted[1];
string value1 = new JavaScriptSerializer().Deserialize<JSON_Deconstructor>(resp).Permitted[0].Delete[0].ToString();
string value2 = new JavaScriptSerializer().Deserialize<JSON_Deconstructor>(resp).Permitted[0].Delete[1].ToString();
==================
JSON_Deconstructor class contents:
public class JSON_Deconstructor
{
public Permitted[] Permitted { get; set; }
public Denied[] Denied { get; set; }
}
==================
Permitted class contents:
public class Permitted
{
public string[] Read { get; set; }
public string[] Update { get; set; }
public string[] Delete { get; set; }
}
=================
JSON response:
{
"Permitted": [
{
"read": [
"MCS:Menu:Admin"
],
"update": [
"MCS:test"
],
"delete": [
"MCS:Menu:Admin",
"MCS:test"
]
}
]
}
First add jsonProperty to your class in order to be able to serialize.
public class Permitted
{
[JsonProperty("read")]
public string[] Read { get; set; }
[JsonProperty("update")]
public string[] Update { get; set; }
[JsonProperty("delete")]
public string[] Delete { get; set; }
}
//Response contains a list of permitted objects in Permitted property
public class PermittedResponse
{
public List<Permitted> Permitted { get; set; }
}
then in you method de serialize your response and loop through results to build your arrays.
List<string> deletedValues = new List<string>();
List<string> readValues = new List<string>();
List<string> updateValues = new List<string>();
PermittedResponse response = JsonConvert.DeserializeObject<PermittedResponse>(serializedJson);
response.Permitted.ForEach(e =>
{
deletedValues = deletedValues.Concat(e.Delete).ToList();
readValues = readValues.Concat(e.Read).ToList();
updateValues = updateValues.Concat(e.Update ).ToList();
});
Use Newtonsoft.Json. You can get it from NuGet. This is very simple and powerful library for Json.
Now, you should create a class, like:
public class Item
{
public List<string> MCS { get; set; } = new List<string>();
}
public class PermitedItem
{
public Item read {get; set;}
public Item update {get; set;}
public Item delete {get; set;}
}
public class MyResponse
{
public List<PermittedItem> Permitted = new List<PermittedItems>();
}
And then you use it like that:
MyResponse result = JsonConvert.DeserializeObject<MyResponse>(jsonAsString);
This should work.
[{"service":"xxx",
"processes":
[
{
"name":"tomcat",
"command":{
"start": "/server/tomcat01/bin/tomcat01.sh start",
"stop": "/server/tomcat01/bin/tomcat01.sh stop",
"restart": "/server/tomcat01/bin/tomcat01.sh restart",
}
}
]
}]
how to get start item value with using c# linq?
Given the following concrete classes:
public class Command
{
public string start { get; set; }
public string stop { get; set; }
public string restart { get; set; }
}
public class Process
{
public string name { get; set; }
public Command command { get; set; }
}
public class Services
{
public string service { get; set; }
public List<Process> processes { get; set; }
}
You can deserialize the json and retrieve a list of all starts with the following:
var json = #"[{""service"":""xxx"", ""processes"": [{""name"":""tomcat"", ""command"":{""start"":""/server/tomcat01/bin/tomcat01.shstart"", ""stop"":""/server/tomcat01/bin/tomcat01.shstop"", ""restart"":""/server/tomcat01/bin/tomcat01.shrestart"", } } ] }]";
var deserialized = JsonConvert.DeserializeObject<List<Services>>(json);
var starts = deserialized.Select(x => x.processes.Select(p => p.command?.start));
Using the Json.Net LINQ-to-JSON API you could do this:
string command = JToken.Parse(json)
.SelectMany(jo => jo.SelectToken("processes"))
.Select(jo => (string)jo.SelectToken("command.start"))
.FirstOrDefault();
...which would return /server/tomcat01/bin/tomcat01.sh start given your JSON input.
Fiddle: https://dotnetfiddle.net/Ft3q2C
It seems that you want to deserialize your json string into C# class.
JavaScriptSerializer jss= new JavaScriptSerializer();
CustomClass tempClass = jss.Deserialize<CustomClass>(jsonString);
jsonString is json data which you mentioned in your question. You can then use linq over your class.
I have Json like below:
[
{
"name": "ts.DatumVon",
"value": "29.10.2015"
},
{
"name": "ts.Von",
"value": "8:00"
},
{
"name": "ts.Bis",
"value": "16:30"
}
]
for this class:
public class TSInfo
{
public TimeSaver ts { get; set; }
[Display(Name = "Status")]
public TSStatus tsStatus { get; set; }
[Display(Name = "Typ")]
public TSTyp tsTyp { get; set; }
public TSAuswahlSteps step { get; set; }
}
How to deserialize this Json string in controller method?
EDIT:
I hope that clarifies it.
public class TimeSaver
{
public DateTime DatumVon { get; set; }
public TimeSpan Von { get; set; }
public TimeSpan Bis { get; set; }
}
I tried something like this:
string tsi = [{"name":"ts.DatumVon","value":"29.10.2015"},{"name":"ts.Von","value":"8:00"},{"name":"ts.Bis","value":"16:30"}]
var dict = JsonConvert.DeserializeObject<List<Dictionary<String,String>>(tsi);
The JSON you provided is a list of dictionaries. So you can deserialize it (using NewtonSoft.Json) like this:
string json = "your json";
var result = JsonConvert.Deserialize<List<Dictionary<String,String>>(json);
How you map the result to your class is up to you.
EDIT the above makes no sense. Sorry for that.
Well, your JSON gave me some headache but I think I fixed it.
The JSON is an array of KeyValuePairs. Every pair describes an attribute of your TimeSaver class. The array as an whole describes the complete class. I don't know of an easy way to convert this JSON to a C# class. What complicates the problem even more is the fact that every attribute has some sort of namespace prefix: ts. The final complication is the date format. That's not a format that's recognized automatically.
My solution converts the JSON to a new JSON describing a TimeSaver object. This new JSON is then deserialized using JsonConvert.
One issue still remains: the TimeSaver.DateVon has become a string.
using System;
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json;
public class Program
{
public static void Main()
{
string tsi = "[{\"name\":\"ts.DatumVon\",\"value\":\"29.10.2015\"},{\"name\":\"ts.Von\",\"value\":\"8:00\"},{\"name\":\"ts.Bis\",\"value\":\"16:30\"}]";
var attributes = JsonConvert.DeserializeObject<List<NameValuePair>>(tsi);
attributes = attributes
.Select(item => new NameValuePair { Name = item.Name.Replace("ts.", ""), Value = item.Value })
.ToList();
var newJson = "{" + String.Join(",", attributes.Select(item => String.Format("\"{0}\":\"{1}\"", item.Name, item.Value))) + "}";
Console.WriteLine(newJson);
var ts = JsonConvert.DeserializeObject<TimeSaver>(newJson);
Console.WriteLine(ts.DatumVon);
Console.WriteLine(ts.Von);
Console.WriteLine(ts.Bis);
}
}
public class NameValuePair
{
public string Name { get; set; }
public string Value { get; set; }
}
public class TimeSaver
{
public String DatumVon { get; set; }
public TimeSpan Von { get; set; }
public TimeSpan Bis { get; set; }
}
I have the following issue with this json :
{
"EVTS": {
"EVT": [
{ "ID": "123456",
"KEY1" : "somekey",
"CATEG": [
"cat1",
"cat2",
"cat3"
]
}
]}
}
and this c# class:
public class myClass{
public string ID { get; set; }
public string KEY1 { get; set; }
public list<string> CATEG { get; set; }
}
public class ESObject1
{
[JsonProperty("EVT")]
public List<myClass> EVT { get; set; }
}
public class ESObject0
{
[JsonProperty("EVTS")]
public ESObject1 EVTS { get; set; }
}
}
here i call the deserializer :
ESObject0 globalobject = JsonConvert.DeserializeObject<ESObject0>(json);
But this last code doesnt work, i throws this exception : System.ArgumentException: Could not cast or convert from System.String to System.Collections.Generic.List1[System.String].`
Instead of list<string> i used string [] and only string nothing seems to work.
how can i deserialize this object correctly please.
Thank you.
There doesn't seem to be any apparent problem wit hyour code as this working example illustrates:
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
public class myClass
{
public string ID { get; set; }
public string KEY1 { get; set; }
public List<string> CATEG { get; set; }
}
public class ESObject1
{
[JsonProperty("EVT")]
public List<myClass> EVT { get; set; }
}
public class ESObject0
{
[JsonProperty("EVTS")]
public ESObject1 EVTS { get; set; }
}
class Program
{
static void Main()
{
string json =
#"{
""EVTS"": {
""EVT"": [
{
""ID"": ""123456"",
""KEY1"": ""somekey"",
""CATEG"": [
""cat1"",
""cat2"",
""cat3""
]
}
]
}
}";
ESObject0 globalobject = JsonConvert.DeserializeObject<ESObject0>(json);
foreach (string item in globalobject.EVTS.EVT[0].CATEG)
{
Console.WriteLine(item);
}
}
}
Maybe you just fed a wrong json value to the deserializer which doesn't look like as the one shown in your question. By the way, the one shown i nyour question is invalid JSON as you are missing a , after KEY1 property declaration.
UPDATE:
Now that you have shown your real JSON (coming from http://donnees.ville.quebec.qc.ca/Handler.ashx?id=69&f=JSON) it appears that there's a row where CATEG is not an array of strings but a simple string:
""CATEG"": ""Conférence""
Now that's a pretty bad design because they are mixing arrays and simple properties. I am afraid that in order to deal with this situation you will need to use JObjects and extract the information you need by testing the actual underlying type.
For example:
var obj = JObject.Parse(json);
var events = (JArray)obj["EVTS"]["EVT"];
foreach (JObject evt in events)
{
var categories = evt["CATEG"];
if (categories is JArray)
{
// you've got a list of strings so you can loop through them
string[] cats = ((JArray)categories)
.Select(x => x.Value<string>())
.ToArray();
}
else
{
// you've got a simple string
string cat = categories.Value<string>();
}
}
I have done this many times with many many headaches. My advice is take the json output and use a tool similar to this to write your class for you (http://json2csharp.com/).
Then go over any nullable variables and add nullable type (ex. using int? for int) where needed.