I m working with Core Web API and I have the challenge to nest different class objects into an ArrayList and send them over the FromBody object, the issue is I have to pack them in a way that on the receiving side I deserialize them into their respective objects.
an example is below.
[Serializable]
public class M1
{
public string Name { get; set; }
public int Age { get; set; }
}
[Serializable]
public class M2 : M1
{
public string Gender { get; set; }
public int Height { get; set; }
}
static void Main(string[] args)
{
try
{
M1 mObj = new M1();
M2 m2Obj = new M2();
ArrayList alist = new ArrayList();
mObj.Name = "Apple";
mObj.Age = 20;
m2Obj.Name = "Banana";
m2Obj.Age = 30;
m2Obj.Gender = "Male";
m2Obj.Height = 6;
alist.Add(mObj);
alist.Add(m2Obj);
string result = string.Empty;
M1 mObjD = new M1();
M2 mObj2D = new M2();
//Method1
try
{
result = Newtonsoft.Json.JsonConvert.SerializeObject(alist, Formatting.Indented);
mObjD = Newtonsoft.Json.JsonConvert.DeserializeObject<M1>(result);
mObj2D = Newtonsoft.Json.JsonConvert.DeserializeObject<M2>(result);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
//Method 2
try
{
result = Newtonsoft.Json.JsonConvert.SerializeObject(mObj, Formatting.Indented);
result = result + Newtonsoft.Json.JsonConvert.SerializeObject(m2Obj, Formatting.Indented);
mObjD = Newtonsoft.Json.JsonConvert.DeserializeObject<M1>(result);
mObj2D = Newtonsoft.Json.JsonConvert.DeserializeObject<M2>(result);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
For the first method its throwing error:
Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'SerliazeDeserliaze.M1' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.
To fix this error either change the JSON to a JSON object (e.g. {"name":"value"}) or change the deserialized type to an array of a type that implements a collection interface (e.g. ICollection, IList) like List that can be deserialized from a JSON array. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array.
Path '', line 1, position 1.
for the second method, it says
Additional text encountered after finished reading JSON content: {. Path '', line 4, position 2.
By doing some hack I have done that different way.
M1 mObj = new M1();
M2 m2Obj = new M2();
ArrayList alist = new ArrayList();
ArrayList alistb = new ArrayList();
mObj.Name = "Apple";
mObj.Age = 20;
m2Obj.Name = "Banana";
m2Obj.Age = 30;
m2Obj.Gender = "Male";
m2Obj.Height = 6;
alist.Add(mObj);
alist.Add(m2Obj);
string result = string.Empty;
M1 mObjD = new M1();
M2 mObj2D = new M2();
string json = JsonConvert.SerializeObject(alist, Formatting.Indented, new KeysJsonConverter(typeof(ArrayList)));
alistb= JsonConvert.DeserializeObject<ArrayList>(json, new KeysJsonConverter(typeof(ArrayList)));
mObjD = Newtonsoft.Json.JsonConvert.DeserializeObject<M1>(alistb[0].ToString());
mObj2D = Newtonsoft.Json.JsonConvert.DeserializeObject<M2>(alistb[1].ToString());
Serializing the list into JSON and then Deserializing it in a reverse way get the job done.
If you serialize list of object, you should deserialize it also into list:
string result = Newtonsoft.Json.JsonConvert.SerializeObject(aList, Formatting.Indented);
List<M1> mObjD = Newtonsoft.Json.JsonConvert.DeserializeObject<List<M1>>(result);
JSON supports the following two data structures,
Collection of name/value pairs - This Data Structure is supported by different programming languages.
Ordered list of values - It includes an array, list, vector or sequence, etc.
JSON has the following styles,
Object
An unordered "name/value" assembly. An object begins with "{" and ends with "}". Behind each "name", there is a colon. And comma is used to separate much "name/value". For example,
var user = {"name":"Manas","gender":"Male","birthday":"1987-8-8"}
Array
Value order set. An array begins with "[" and end with "]". And values are separated with commas. For example,
var userlist = [{"user":{"name":"Manas","gender":"Male","birthday":"1987-8-8"}},
{"user":{"name":"Mohapatra","Male":"Female","birthday":"1987-7-7"}}]
String
Any quantity Unicode character assembly which is enclosed with quotation marks. It uses backslash to escape.
var userlist = "{\"ID\":1,\"Name\":\"Manas\",\"Address\":\"India\"}"
We can implement JSON Serialization/Deserialization in the following three ways:
Using JavaScriptSerializer class
Using DataContractJsonSerializer class
Using JSON.NET library
Using DataContractJsonSerializer
DataContractJsonSerializer class helps to serialize and deserialize JSON.
It is present in namespace System.Runtime.Serialization.Json which is
available in assembly System.Runtime.Serialization.dll. Using the
class we can serialize an object into JSON data and deserialize JSON
data into an object.
Let's say there is Employee class with properties such as name, address, and property values also assigned. Now we can convert the Employee class instance to the JSON document. This JSON document can be deserialized into the Employee class or another class with an equivalent data contract. The following code snippets demonstrate about serialization and deserialization.
Let's create a custom class BlogSite for serialization and deserialization,
[DataContract]
class BlogSite
{
[DataMember]
public string Name { get; set; }
[DataMember]
public string Description { get; set; }
}
C# Serialization
In Serialization, it converts a custom .Net object to a JSON string. In the following code, it creates an instance of BlogSiteclass and assigns values to its properties. Then we create an instance of DataContractJsonSerializer class by passing the parameter BlogSite class and create an instance of MemoryStream class to write object(BlogSite). Lastly it creates an instance of StreamReader class to read JSON data from MemorySteam object.
BlogSite bsObj = new BlogSite()
{
Name = "C-sharpcorner",
Description = "Share Knowledge"
};
DataContractJsonSerializer js = new DataContractJsonSerializer(typeof(BlogSite));
MemoryStream msObj = new MemoryStream();
js.WriteObject(msObj, bsObj);
msObj.Position = 0;
StreamReader sr = new StreamReader(msObj);
// "{\"Description\":\"Share Knowledge\",\"Name\":\"C-sharpcorner\"}"
string json = sr.ReadToEnd();
sr.Close();
msObj.Close();
C# Deserialization
In Deserialization, it does the opposite of Serialization, which means it converts JSON string to a custom .Net object. In the following code, it creates an instance of BlogSite class and assigns values to its properties. Then we create an instance of DataContractJsonSerializer class by passing the parameter BlogSite class and creating an instance of MemoryStream class to write an object(BlogSite). Lastly, it creates an instance of StreamReader class to read JSON data from MemorySteam object.
string json = "{\"Description\":\"Share Knowledge\",\"Name\":\"C-sharpcorner\"}";
using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(json)))
{
// Deserialization from JSON
DataContractJsonSerializer deserializer = new DataContractJsonSerializer(typeof(BlogSite));
BlogSite bsObj2 = (BlogSite)deserializer.ReadObject(ms);
Response.Write("Name: " + bsObj2.Name); // Name: C-sharpcorner
Response.Write("Description: " + bsObj2.Description); // Description: Share Knowledge
}
C# Using JavaScriptJsonSerializer
JavaScriptSerializer is a class that helps to serialize and deserialize JSON. It is present in the namespace System.Web.Script.Serialization is available in assembly System.Web.Extensions.dll. To serialize a .Net object to JSON string use the Serialize method. It's possible to deserialize JSON string to .Net object using Deserialize or DeserializeObject methods. Let's see how to implement serialization and deserialization using JavaScriptSerializer.
Following code, a snippet is to declare a custom class of BlogSites type.
class BlogSites
{
public string Name { get; set; }
public string Description { get; set; }
}
C# Serialization
In Serialization, it converts a custom .Net object to a JSON string. In the following code, it creates an instance of BlogSiteclass and assigns some values to its properties. Then we create an instance of JavaScriptSerializer and call Serialize() method by passing object(BlogSites). It returns JSON data in string format.
// Creating BlogSites object
BlogSites bsObj = new BlogSites()
{
Name = "C-sharpcorner",
Description = "Share Knowledge"
};
// Serializing object to json data
JavaScriptSerializer js = new JavaScriptSerializer();
string jsonData = js.Serialize(bsObj); // {"Name":"C-sharpcorner","Description":"Share Knowledge"}
C# Deserialization
In Deserialization, it does the opposite of Serialization which means it converts JSON string to custom .Net object. In the following code, it creates a JavaScriptSerializer instance and calls Deserialize() by passing JSON data. It returns a custom object (BlogSites) from JSON data.
// Deserializing json data to object
JavaScriptSerializer js = new JavaScriptSerializer();
BlogSites blogObject = js.Deserialize<BlogSites>(jsonData);
string name = blogObject.Name;
string description = blogObject.Description;
// Other way to whithout help of BlogSites class
dynamic blogObject = js.Deserialize<dynamic>(jsonData);
string name = blogObject["Name"];
string description = blogObject["Description"];
C# Using Json.NET
Json.NET is a third-party library that helps conversion between JSON text and .NET object using the JsonSerializer. The JsonSerializer converts .NET objects into their JSON equivalent text and back again by mapping the .NET object property names to the JSON property names. It is open-source software and free for commercial purposes.
The following are some awesome features,
Flexible JSON serializer for converting between .NET objects and JSON.
LINQ to JSON for manually reading and writing JSON.
High performance, faster than .NET's built-in JSON serializers.
Easy to read JSON.
Convert JSON to and from XML.
Supports .NET 2, .NET 3.5, .NET 4, Silverlight and Windows Phone.
Let’s start learning how to install and implement:
In Visual Studio, go to Tools Menu -> Choose Library Package Manager -> Package Manager Console. It opens a command window where we need to put the following command to install Newtonsoft.Json.
Install-Package Newtonsoft.Json
OR
In Visual Studio, Tools menu -> Manage Nuget Package Manager Solution and type “JSON.NET” to search it online. Here's the figure,
Json.NET
Serialization
In Serialization, it converts a custom .Net object to a JSON string. In the following code, it creates an instance of BlogSiteclass and assigns some values to its properties. Then it calls static method SerializeObject() of JsonConvert class by passing object(BlogSites). It returns JSON data in string format.
// Creating BlogSites object
BlogSites bsObj = new BlogSites()
{
Name = "C-sharpcorner",
Description = "Share Knowledge"
};
// Convert BlogSites object to JOSN string format
string jsonData = JsonConvert.SerializeObject(bsObj);
Response.Write(jsonData);
C# Deserialization
In Deserialization, it does the opposite of Serialization which means it converts JSON string to custom .Net object. In the following code, it calls the static method DeserializeObject() of the JsonConvert class by passing JSON data. It returns a custom object (BlogSites) from JSON data.
string json = #"{
'Name': 'C-sharpcorner',
'Description': 'Share Knowledge'
}";
BlogSites bsObj = JsonConvert.DeserializeObject<BlogSites>(json);
Response.Write(bsObj.Name);
JSON.NET, visit here.
In Visual Studio, Tools menu -> Manage Nuget Package Manger Solution and type “JSON.NET” to search it online. Here's the
Related
The JSON string that I want to parse is the response from the API and the response may not have fixed properties. So cannot create a class with properties to parse the JSON string.
I tried to parse the JSON string to dynamic/Expando object but it does not parse the nested objects,
For example,
string jsonText = "[{ \"FirstName\":\"John\",\"LastName\":\"K\",\"Address\":{\"Line1\":\"Sector 6\"} }]";
I am using the below code for deserializing the JSON string,
public static T Deserialize<T>(this string str) where T : class
{
var ser = new DataContractJsonSerializer(typeof(T), new DataContractJsonSerializerSettings
{
UseSimpleDictionaryFormat = true,
IgnoreExtensionDataObject=true
});
using (var ms = new MemoryStream(Encoding.UTF8.GetBytes(str)))
{
return (T)ser.ReadObject(ms);
}
}
IEnumerable<ExpandoObject> contactObject = Deserialize<IEnumerable<ExpandoObject>>(jsonText);
This code fails to parse the Address property. It simply shows the object instead of the actual value.
Due to project requirement cannot use NewtonsoftJSON and System.Text.Json.
How I can parse complex JSON string to dynamic object without creating a custom class using System.Runtime.Serialization.Json?
I have to extract a part of json-string using .net or newtonsoft json.
JSON:
var json = "{\"method\":\"subtract\",\"parameters\":{\"minuend\":\"SOME_CUSTOM_JSON_OBJECT_DIFFERENT_FOR_EACH_METHOD\",\"subtrahend\":23}}";
C# Class:
class MyJson{
public string method { get; set; }
//public string parameters {get; set;}
public object parameters {get; set;}
}
I do not need to parse all the children of "parameters" json-object. "parameters" could be a very big object ([{obj1}...{obj1000}], objX of 1000 fields), parse which would be not performant.
I would like i.e. to pass it exactly as it is on some point, so conversion "string-C#object-string" would be redundant.
I do not want use Regexp or string transformations (string.Substring, Split and co), because of error margin, I know that all .net and newtonsoft string transformations based.
Question 1: if I define a property of type "object", how newtonsoft will handle this? (Documentation is worse than msdn, so I'm looking for the input from you, who already tried this).
static void Main(string[] args)
{
var json = "{\"method\":\"subtract\",\"parameters\":{\"minuend\":42,\"subtrahend\":23}}";
var data = JsonConvert.DeserializeObject<MyJson>(j);
// what internal representaion of data.parameters?
// How is it actually converted from json-string to an C# object (JObject/JsonObject).
}
In perfect case:
"parameters" is a string and calling
ExtractMyJson(jsonString)
gives me the json string of parameters.
Basically I need the newtonsoft version of
string ExtractMyJson(jsonString){
var p1 = jsonString.Split(",");
// .. varios string transformations
return pParams;
}
Note: please don't reference "dynamic" keyword or ask why no string transformations, it's the very specific question.
If you know that your parameters are unique you can do something like this:
class MyJson
{
public string method { get; set; }
public Dictionary<string,object> parameters { get; set; }
}
................
string json = "{\"method\":\"subtract\",\"parameters\":{\"minuend\":{\"img\": 3, \"real\": 4},\"subtrahend\":23}}";
var data = JsonConvert.DeserializeObject<MyJson>(json);
If you let it as object is going to receive the type Newtonsoft.Json.Linq.JObject.
Have you tried JTOKEN?
It is a rather simple solution to partially read basic or nested JSONs as described in this post.
For a nested JSON
{
"key1": {
"key11": "value11",
"key12": "value12"
}
"key2": "value2"
}
it would look like this
JToken token = JToken.Parse(json);
var value12 = token.SelectToken("key1.key12");
to get the element of the key "key12.
I think this could go nicely with your problem.
Well Objects are treated the same way your parent object is treated. It will start from the base of the graph. So if you have something like:
Person
{
Address Address {get;set;}
}
The Json will start Deserializing Address and then add in the Person object.
If you want to limit thesize of the graph depth you can use a setting like :
JsonConvert.DeserializeObject<List<IList<IList<string>>>>(json, new JsonSerializerSettings
{
MaxDepth = 2
});
For more configurations of the JsonSerializer check JsonSerializerSettings
If your field is an object then that object will have the KeyValuePair of every property that it holds, based on that when you cast that field you can access that type.(the behaviour is the same as assigning a type to an object in C#).
Update: So if you question using JsonObject or type, well JObject is and intermediary way to construct the json format in a generic format. But using the Type deserializatin means you can ignore properties you are not interested in. Mapping to a json with a type makes more sense because it creates a new object and dismisses the old JObject.
I have the following raw JSON string:
[\"Hello World!\",\"94952923696694934\",\"MyChannel\"]
I have tried the following without luck:
My custom object class:
public class MyObject
{
public string msg { get; set; }
public string id { get; set; }
public string chn { get; set; }
}
JSON string:
string str = "[\"Hello World!\",\"94952923696694934\",\"MyChannel\"]";
1st attempt at deserilization using System.Web.Script.Serialization:
JavaScriptSerializer serializer = new JavaScriptSerializer();
MyObject obj1 = serializer.Deserialize<MyObject>(str);
2nd attempt at deserilization using Newtonsoft.Json:
MyObject obj2 = JsonConvert.DeserializeObject<MyObject>(str);
Both attempts fail. Any suggestions?
You have a JSON array of strings, not an object with property names.
So the best you can do here is to deserialize the array:
IEnumerable<string> strings =
JsonConvert.DeserializeObject<IEnumerable<string>>(str);
...then use the resulting sequence strings as you see fit.
With PubNub, you can just pass in the native String, Dictionary, or Array, and we'll JSON encode it for you on the publish side, and auto JSON decode for you on the subscriber side.
It's because your 'custom object' isn't equivalent to the json representation. The json you're deserializing is just a string[] in C# (you can also use List<string> or other IEums).
So in code you're looking for;
string[] theJson = JsonConvert.DeserializeObject<string[]>(str);
MyObject would be used for the following json;
{
"msg":"Hello World!",
"id":"94952923696694934",
"chn":"MyChannel"
}
I'm really bad with C# and would like your help doing the following; I am currently passing a Json Array to my WCF webservice. I need to take the json array and insert it into a list. I have no idea to deserialize in C#. Please suggest to me what is the best way of achieving this. My code looks as follows:
public String UpdateOrderAddress(Stream userInfo)
{
try
{
StreamReader reader = new StreamReader(userInfo);
string JSONdata = reader.ReadToEnd();
if (JSONdata == null)
{
return "null";
}
return JSONdata; // Success !
}
catch (Exception e)
{
return e.ToString();
}
}
This is the data in the string that I get from the reader
[{"date":"2013-02-22 15:30:374:021","id":"1","description":"test","name":"test"},
"date":"2013-02-25 11:56:926:020","id":"2","description":"ghy","name":"fhh"},
"date":"2013-02-25 11:56:248:026","id":"3","description":"ghfm","name":"run"}]
The code you posted doesn't show how are you trying to deserialize your json string so I don't really follow what's the relevance here but in any case, this is how to deserialize JSON into a concrete C# class.
Create a class that matches the structure of your Javascript objects as so:
public class Data
{
public string Date {get;set;}
public int ID {get;set;}
public string Description {get;set;}
public string Name {get;set;}
}
Deserialize it using the JavascriptSerializer as so:
var deserializedData = new JavaScriptSerializer().Deserialize<List<Data>>(jsonString);
Note that your original JSON string is incorrectly formatted. It's missing the opening { on each element of the array. It should really be:
[{"date":"2013-02-22
15:30:374:021","id":"1","description":"test","name":"test"},
{"date":"2013-02-25
11:56:926:020","id":"2","description":"ghy","name":"fhh"},
{"date":"2013-02-25
11:56:248:026","id":"3","description":"ghfm","name":"run"}]
Now, if you attempt to deserialize the above, as so:
string json = #"[{""date"":""2013-02-22 15:30:374:021"",""id"":""1"",""description"":""test"",""name"":""test""},
{""date"":""2013-02-25 11:56:926:020"",""id"":""2"",""description"":""ghy"",""name"":""fhh""},
{""date"":""2013-02-25 11:56:248:026"",""id"":""3"",""description"":""ghfm"",""name"":""run""}]";
var deserializedData = new JavaScriptSerializer().Deserialize<List<Data>>(json);
You'll get a nice List<Data> back.
Also note that I didn't use a DateTime field for the corresponding date field in your Javascript object, the reason being that your sample dates are not valid DateTimes or at least a DateTime object cannot be created from that string representation. For instance, "15:30:374:021" makes no sense - I would imagine that 374 is the seconds field...
You need to add a reference to System.Web.Extensions to be able to use the JavascriptSerializer.
You can create a representative class with your required properties to hold the values and use the JavascriptSerializer class. Call the Deserialize<T> method specifying your type to deserialize the JSON into your code.
Links in class names for reference.
You can use Newtonsoft.Json Library. All you will need to do is:
List<YourClass> yourClassList = JsonConvert.DeserializeObject<List<YourClass>>(JSONdata);
You find more information, even samples here
I have an object model that looks like this:
public MyObjectInJson
{
public long ObjectID {get;set;}
public string ObjectInJson {get;set;}
}
The property ObjectInJson is an already serialized version an object that contains nested lists. For the moment, I'm serializing the list of MyObjectInJson manually like this:
StringBuilder TheListBuilder = new StringBuilder();
TheListBuilder.Append("[");
int TheCounter = 0;
foreach (MyObjectInJson TheObject in TheList)
{
TheCounter++;
TheListBuilder.Append(TheObject.ObjectInJson);
if (TheCounter != TheList.Count())
{
TheListBuilder.Append(",");
}
}
TheListBuilder.Append("]");
return TheListBuilder.ToString();
I wonder if I can replace this sort of dangerous code with JavascriptSerializer and get the same results.
How would I do this?
If using .Net Core 3.0 or later;
Default to using the built in System.Text.Json parser implementation.
e.g.
using System.Text.Json;
var json = JsonSerializer.Serialize(aList);
alternatively, other, less mainstream options are available like Utf8Json parser and Jil: These may offer superior performance, if you really need it but, you will need to install their respective packages.
If stuck using .Net Core 2.2 or earlier;
Default to using Newtonsoft JSON.Net as your first choice JSON Parser.
e.g.
using Newtonsoft.Json;
var json = JsonConvert.SerializeObject(aList);
you may need to install the package first.
PM> Install-Package Newtonsoft.Json
For more details see and upvote the answer that is the source of this information.
For reference only, this was the original answer, many years ago;
// you need to reference System.Web.Extensions
using System.Web.Script.Serialization;
var jsonSerialiser = new JavaScriptSerializer();
var json = jsonSerialiser.Serialize(aList);
You can also use Json.NET. Just download it at http://james.newtonking.com/pages/json-net.aspx, extract the compressed file and add it as a reference.
Then just serialize the list (or whatever object you want) with the following:
using Newtonsoft.Json;
string json = JsonConvert.SerializeObject(listTop10);
Update: you can also add it to your project via the NuGet Package Manager (Tools --> NuGet Package Manager --> Package Manager Console):
PM> Install-Package Newtonsoft.Json
Documentation: Serializing Collections
There are two common ways of doing that with built-in JSON serializers:
JavaScriptSerializer
var serializer = new JavaScriptSerializer();
return serializer.Serialize(TheList);
DataContractJsonSerializer
var serializer = new DataContractJsonSerializer(TheList.GetType());
using (var stream = new MemoryStream())
{
serializer.WriteObject(stream, TheList);
using (var sr = new StreamReader(stream))
{
return sr.ReadToEnd();
}
}
Note, that this option requires definition of a data contract for your class:
[DataContract]
public class MyObjectInJson
{
[DataMember]
public long ObjectID {get;set;}
[DataMember]
public string ObjectInJson {get;set;}
}
public static string JSONSerialize<T>(T obj)
{
string retVal = String.Empty;
using (MemoryStream ms = new MemoryStream())
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
serializer.WriteObject(ms, obj);
var byteArray = ms.ToArray();
retVal = Encoding.UTF8.GetString(byteArray, 0, byteArray.Length);
}
return retVal;
}
.NET already supports basic Json serialization through the System.Runtime.Serialization.Json namespace and the DataContractJsonSerializer class since version 3.5. As the name implies, DataContractJsonSerializer takes into account any data annotations you add to your objects to create the final Json output.
That can be handy if you already have annotated data classes that you want to serialize Json to a stream, as described in How To: Serialize and Deserialize JSON Data. There are limitations but it's good enough and fast enough if you have basic needs and don't want to add Yet Another Library to your project.
The following code serializea a list to the console output stream. As you see it is a bit more verbose than Json.NET and not type-safe (ie no generics)
var list = new List<string> {"a", "b", "c", "d"};
using(var output = Console.OpenStandardOutput())
{
var writer = new DataContractJsonSerializer(typeof (List<string>));
writer.WriteObject(output,list);
}
On the other hand, Json.NET provides much better control over how you generate Json. This will come in VERY handy when you have to map javascript-friendly names names to .NET classes, format dates to json etc.
Another option is ServiceStack.Text, part of the ServicStack ... stack, which provides a set of very fast serializers for Json, JSV and CSV.
building on an answer from another posting.. I've come up with a more generic way to build out a list, utilizing dynamic retrieval with Json.NET version 12.x
using Newtonsoft.Json;
static class JsonObj
{
/// <summary>
/// Deserializes a json file into an object list
/// Author: Joseph Poirier 2/26/2019
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="fileName"></param>
/// <returns></returns>
public static List<T> DeSerializeObject<T>(string fileName)
{
List<T> objectOut = new List<T>();
if (string.IsNullOrEmpty(fileName)) { return objectOut; }
try
{
// reading in full file as text
string ss = File.ReadAllText(fileName);
// went with <dynamic> over <T> or <List<T>> to avoid error..
// unexpected character at line 1 column 2
var output = JsonConvert.DeserializeObject<dynamic>(ss);
foreach (var Record in output)
{
foreach (T data in Record)
{
objectOut.Add(data);
}
}
}
catch (Exception ex)
{
//Log exception here
Console.Write(ex.Message);
}
return objectOut;
}
}
call to process
{
string fname = "../../Names.json"; // <- your json file path
// for alternate types replace string with custom class below
List<string> jsonFile = JsonObj.DeSerializeObject<string>(fname);
}
or this call to process
{
string fname = "../../Names.json"; // <- your json file path
// for alternate types replace string with custom class below
List<string> jsonFile = new List<string>();
jsonFile.AddRange(JsonObj.DeSerializeObject<string>(fname));
}
If you're doing this in the context of a asp.Net Core API action, the conversion to Json is done implicitly.
[HttpGet]
public ActionResult Get()
{
return Ok(TheList);
}
using System;
using System.Text.Json;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
List<ErrorDetail> aList = new List<ErrorDetail>();
ErrorDetail a = new ErrorDetail{ ColumnName="aaa", ErrorText="abbbb"};
ErrorDetail c = new ErrorDetail{ ColumnName="ccc", ErrorText="cccc"};
ErrorDetail b = new ErrorDetail{ ColumnName="ccc", ErrorText="cccc"};
aList.Add(a);
aList.Add(b);
aList.Add(c);
var json = JsonSerializer.Serialize(aList);
Console.WriteLine(json);
}
public class ErrorDetail
{
public string ColumnName { get; set; }
public string ErrorText { get; set; }
}
}
I tried the other answers here to serialize parameters for a POST request, but my backend did not like the fact that I was sending up a string version of my array. I did not want to have to always check if the type of a parameter is a string and convert it to an array.
I'm using Json.NET (which is now built into C#), and I convert my List to an array and let the converter handle the rest.
public class MyObjectInJson
{
public long ID;
public OtherObject[] array;
}
You can convert your List into an array using list.ToArray();
And then finally using the JsonConvert, you can turn the entire object into a string:
string jsonString = JsonConvert.SerializeObject(objectInJson);
Hope this helps someone else.