Serialize JSON from List<T> and Show Values - c#

I have a list of a custom object with two properties that needs to be serialized into JSON. Here is the object:
public class IndexData
{
public string ColumnName { get; set; }
public string Data { get; set; }
}
I need the JSON for the List to be returned like this:
{ "IndexData" : [
{ "Column1": "Data1",
"Column2": "Data2"
}
]
}
Is this possible?

List<IndexData> list = new List<IndexData>()
{
new IndexData(){ColumnName="column1",Data="data1"},
new IndexData(){ColumnName="column2",Data="data2"},
};
//Using Json.Net
var json1 = JsonConvert.SerializeObject(
new {IndexData=list.ToDictionary(x => x.ColumnName, x => x.Data)});
//Using JavaScriptSerializer
var json2 = new JavaScriptSerializer().Serialize(
new { IndexData = list.ToDictionary(x => x.ColumnName, x => x.Data) });

Use JavaScriptSerializer
var indexdata = new IndexData();
var json = new JavaScriptSerializer().Serialize(indexdata);
OR DataContractJsonSerializer
MemoryStream s = new MemoryStream();
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(IndexData));
s.Position = 0;
StreamReader sr = new StreamReader(s);
var json = sr.ReadToEnd();

I'm a big fan of Json.Net
You can use the SerializeObject call to simple serialize your object:
var list = new List<IndexData> {new IndexData {ColumnName = "Foo", Data = "Bar"}};
var output = JsonConvert.SerializeObject(list);
output will then be set to
[{"ColumnName":"Foo","Data":"Bar"}]

Related

Serialize and deserialize json c#

I'm trying to build a json (with success) but now i need to deserialize the json, it's the first time i'm using json so i don't really know what do to. I got that's exception when i try to deserialize:
Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'System.Collections.Generic.Dictionary`2[System.String,Boosty.AltsInfos[]]' 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 or a type that implements a collection interface (e.g. ICollection, IList) like List<T> 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.
Serializer:
var json = new List<Alts>();
List<AltsInfos> p1 = new List<AltsInfos> { new AltsInfos { alts_name = "JeSaisPas", alts_email = "truc2fou#g.com", alts_pass = "azerty", alts_type = AltsInfos.AltType.Microsoft } };
json.Add(new Alts { account = p1 });
List<AltsInfos> p2 = new List<AltsInfos> { new AltsInfos { alts_name = "TrucBidule", alts_email = "trucmachun#g.com", alts_pass = "azerty2.0", alts_type = AltsInfos.AltType.Microsoft } };
json.Add(new Alts { account = p2 });
string jsonString = JsonConvert.SerializeObject(json, Formatting.None, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore, Formatting = Formatting.Indented });
File.WriteAllText(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + #"/BoostyLauncher" + #"/alts.json", jsonString);
Deserializer
using (StreamReader sr = new StreamReader(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + #"/BoostyLauncher" + #"/alts.json"))
{
string json = sr.ReadToEnd();
List<AltsInfos> alts = JsonConvert.DeserializeObject<List<AltsInfos>>(json);
foreach (var item in alts)
Console.WriteLine(item.alts_email);
}
Type containers
class Alts
{
public List<AltsInfos> account { get; set; }
}
class AltsInfos
{
public string alts_name { get; set; }
public string alts_email { get; set; }
public string alts_pass { get; set; }
public AltType alts_type { get; set; }
public enum AltType
{
[EnumMember(Value = "Microsoft")]
Microsoft,
[EnumMember(Value = "Altening")]
Altening
}
}
All i want is to extract alts_name for each account category. Also i don't know how i set the enum in the json it's set to 0.
[
{
"account": [
{
"alts_name": "JeSaisPas",
"alts_email": "truc2fou#g.com",
"alts_pass": "azerty",
"alts_type": 0
}
]
},
{
"account": [
{
"alts_name": "TrucBidule",
"alts_email": "trucmachun#g.com",
"alts_pass": "azerty2.0",
"alts_type": 0
}
]
}
]
You need to fix a bug in your deserialize code. Instead of List< AltsInfos > use List< Alts >
List<Alts> alts = JsonConvert.DeserializeObject<List<Alts>>(jsonString);
foreach (var alt in alts)
foreach (var item in alt.account)
Console.WriteLine(item.alts_email);
or you can use LINQ
List<string> emails = alts.SelectMany(a => a.account.Select(s => s.alts_email)).ToList();
and BTW if you want a json string to be indented, fix the serializer options too
string jsonString = JsonConvert.SerializeObject(json, Newtonsoft.Json.Formatting.Indented, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore});
I have made changes in deserialized line.
should always deserialze into same class (which serialized into json) that is List< Alts >.
var json = new List<Alts>();
List<AltsInfos> p1 = new List<AltsInfos> { new AltsInfos { alts_name = "JeSaisPas", alts_email = "truc2fou#g.com", alts_pass = "azerty", alts_type = AltType.Microsoft } };
json.Add(new Alts { account = p1 });
List<AltsInfos> p2 = new List<AltsInfos> { new AltsInfos { alts_name = "TrucBidule", alts_email = "trucmachun#g.com", alts_pass = "azerty2.0", alts_type = AltType.Microsoft } };
json.Add(new Alts { account = p2 });
string jsonString = JsonConvert.SerializeObject(json, Formatting.None, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore, Formatting = Formatting.Indented });
**List<Alts>** alts = JsonConvert.DeserializeObject<**List<Alts>**>(jsonString);
Please let me know if it solve your problem otherwise will try to explain more.

Generic JSON parser to CustomObject

I have a JSON content like:
{
"ABCD1":[{"gopName":"JHIKJUS"},{"gopName":"LKKJHGYT"}],
"CBFD1":[{"gopName":"HT"},{"gopName":"OP"}]
}
I have created one custom Class i.e.
public class DeskGopMapper
{
public List<string> GopName { get; set; }
public string DeskName { get; set; }
}
Need to know how can we write a custom parser so that it should not be tightly coupled.
Have tried something like:
class Program
{
static void Main(string[] args)
{
using (var stream = File.OpenRead(#"sample.txt"))
using (var reader = new StreamReader(stream))
{
var line = reader.ReadToEnd();
var rawObj = JObject.Parse(line);
List<DeskGopMapper> map = new List<DeskGopMapper>();
foreach (var obj in rawObj)
{
var m = new DeskGopMapper {DeskName = obj.Key, GopName = new List<string>()};
foreach (var prop in obj.Value)
{
m.GopName.Add(prop["gopName"].ToString());
}
map.Add(m);
}
}
}
}
Though i am not very much convinced with way of parsing.
What is the better way to achieve Parsing the JSON response into List<DeskGopMapper> ?
You can use Json.Net's LINQ-to-JSON API to simplify your code:
string json = File.ReadAllText(#"sample.txt");
List<DeskGopMapper> map = JObject.Parse(json)
.Properties()
.Select(p => new DeskGopMapper
{
DeskName = p.Name,
GopName = p.Value.Children<JObject>()
.Select(j => (string)j["gopName"])
.ToList()
})
.ToList();
Demo fiddle: https://dotnetfiddle.net/0d2ZzH

Deserializing JSON with dynamic property

I have to deserialize a JSON response(from a wep API) . The problem is that this API returns JSON with dynamic property. Had it been like
{
"employees":
[{
"employeeCode": "ABC",
"cityId": 123
},{
"employeeCode": "DEF",
"cityId": 234
}]
}
it would have been perfect but the response is string and is returned like:
var response = #"{"ABC": 123, "DEF": 234}";
Where the first property is "EmployeeCode" and the second property is "CityId". How can I use JSON.Net to serialize it into the following class?
public class Employees
{
public string employeeCode {get; set;}
public string cityId {get; set;}
}
Regarding my comment maybe it us better to write the example of what I ment:
string json = #"{""ABC"": 123, ""DEF"": 234}";
var employees = JsonConvert.DeserializeObject<Dictionary<string, int>>(json).Select(x => new Employees() { employeeCode = x.Key, cityId = x.Value });
You'll need:
using System.IO;
using System.Text;
using System.Runtime.Serialization.Json;
public static string Serialize<T>(T obj)
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
MemoryStream ms = new MemoryStream();
serializer.WriteObject(ms, obj);
string retVal = Encoding.UTF8.GetString(ms.ToArray());
return retVal;
}
public static T Deserialize<T>(string json)
{
T obj = Activator.CreateInstance<T>();
MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(json));
DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
obj = (T)serializer.ReadObject(ms);
ms.Close();
return obj;
}

Serializing .NET object to JSON

I tried the following code to serialize a .NET object to JSON, but i keep getting blank text. What am I doing wrong?
[DataContract]
public class JsonObject2
{
[DataMember(Name = "field1")]
string field1 { get; set; }
[DataMember(Name = "field2")]
string field2 { get; set; }
[DataMember(Name = "field3")]
string[] test = { "heshan", "perera" };
}
The object, I attempt to serialize and display the resulting JSON string in a message box, but all i get is blank.
MemoryStream s = new MemoryStream();
DataContractJsonSerializer dcjs2 = new DataContractJsonSerializer((typeof(JsonObject2)));
JsonObject2 obj2 = new JsonObject2();
dcjs2.WriteObject(s, obj2);
StreamReader r = new StreamReader(s);
String x = r.ReadToEnd();
MessageBox.Show(x);
Try adding:
s.Position = 0;
just before you create the StreamReader.

How to decode a JSON string using C#?

I'm looking for an example code/lib to decode a JSON string using C#.
To encode I can do this:
var data = new Dictionary<string,string>();
data.Add("..", "...");
var json_encoded = new JavaScriptSerializer().Serialize(data);
but how do I decode?
var json_decoded = ??
You can do this:
var data = new Dictionary<string, string>();
data.Add("foo", "baa");
JavaScriptSerializer ser = new JavaScriptSerializer();
var JSONString = ser.Serialize(data); //JSON encoded
var JSONObj = ser.Deserialize<Dictionary<string, string>>(JSONString); //JSON decoded
Console.Write(JSONObj["foo"]); //prints: baa
This will take JSON and convert it to a strongly typed class of which you specify (T)
public static T Deserialize<T>(string json)
{
var obj = Activator.CreateInstance<T>();
using(var ms = new MemoryStream(Encoding.Unicode.GetBytes(json)))
{
var serializer = new DataContractJsonSerializer(obj.GetType());
obj = (T) serializer.ReadObject(ms);
return obj;
}
}
This will take a class and serialize it as JSON
public static string Serialize<T>(T obj)
{
var serializer = new DataContractJsonSerializer(obj.GetType());
using (var ms = new MemoryStream())
{
serializer.WriteObject(ms, obj);
return Encoding.Default.GetString(ms.ToArray());
}
}
Note: In the first example you will need to have a backing class to specify what type T is. So if you told it that T is of type User you would need to have this specified somewhere:
public class User
{
public string Username { get; set; }
public string Firstname { get; set; }
}

Categories

Resources