How to decode a JSON string using C#? - 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; }
}

Related

Object to base 64 JSON file

I have an object T. I need to send the file representation of it into a web service. Without saving the file to a temp file.
WebService method:
myClient.SendFile(
new SendFileData{
id = "1",
fileName = "Foo",
fileType = "json",
fileContent = base64, // string Base64 variable here
}
To get the Base64 of a file I use :
public static string FileToBase64(string path) => FileToBase64(File.ReadAllBytes(path));
public static string FileToBase64(Byte[] bytes) => Convert.ToBase64String(bytes);
I have made those method to work on a temp file stored in a directory. saving the Json to file using :
using (StreamWriter file = File.CreateText(tempPath))
{
JsonSerializer serializer = new JsonSerializer();
serializer.Serialize(file, _data);
}
And reading it like:
Directory.GetFiles(directory).Where().Select(x=> new {
fi = new FileInfo(f),
name = Path.GetFileNameWithoutExtension(f),
ext = Path.GetExtension(f).Trim('.'),
content = FileBase64Helper.FileToBase64(f)
})
I try to make a in memory file and convert it to b64 like:
public void Demo()
{
var myObject = new CustomType { Id = 1, Label = "Initialisation of a custom object" };
var stringRepresentation =
JsonConvert.SerializeObject(myObject, Formatting.Indented, new JsonSerializerSettings { });
SendFileData dataProjection = new SendFileData { };
var result = FakeClient.SendFile(dataProjection);
}
public class CustomType
{
public string Label { get; set; }
public int Id { get; set; }
}
public static class FakeClient
{
public static bool SendFile(SendFileData data) => true;
}
public class SendFileData
{
public string id { get; set; }
public string fileName { get; set; }
public string fileType { get; set; }
public string fileContent { get; set; }
}
Comparaison between direct convertion and FileReadByte:
var myObject = new CustomType { Id = 1, Label = "Initialisation of a custom object" };
var stringRepresentation = JsonConvert.SerializeObject(myObject, Formatting.Indented, new JsonSerializerSettings { });
var directSerialization = Convert.ToBase64String(Encoding.UTF8.GetBytes(stringRepresentation));
var tempPath = #"test.json";
using (StreamWriter file = File.CreateText(tempPath))
{
JsonSerializer serializer = new JsonSerializer();
serializer.Serialize(file, myObject);
}
var fromFile = FileBase64Helper.FileToBase64(tempPath);
SendFileData dataProjection = new SendFileData { };
var result = FakeClient.SendFile(dataProjection);
Direct serialization:
ew0KICAiTGFiZWwiOiAiSW5pdGlhbGlzYXRpb24gb2YgYSBjdXN0b20gb2JqZWN0IiwNCiAgIklkIjogMQ0KfQ==
From file
eyJMYWJlbCI6IkluaXRpYWxpc2F0aW9uIG9mIGEgY3VzdG9tIG9iamVjdCIsIklkIjoxfQ==
If you're question is as follows and if i understand it correctly:
"Does File.ReadAllBytes add additional information about the file in it's return value, or is the return value equal to just having the content of the file as a byte array?"
Answer:
According to Microsoft Documentation, it will return the content of the file as a byte array.
Hope this helps!
Source: https://learn.microsoft.com/en-us/dotnet/api/system.io.file.readallbytes?view=netframework-4.7.2
EDIT: Decoding the base64, i found this:
The difference in the base64 encoded values is the json formatting, nothing else :D
Direct serialization:
From file:

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

XML Serialize and deserialize performance comparison

This question asked in different websites but i could not find any useful answer, and still im having some performance issues.
I have two serializer method in my common layer application
public static string Serializer(object o)
{
var x = new XmlSerializer(o.GetType());
var writer = new StringWriter();
var xmlWriter = XmlWriter.Create(writer, new XmlWriterSettings { OmitXmlDeclaration = true });
var emptyNs = new XmlSerializerNamespaces(new[] { XmlQualifiedName.Empty });
x.Serialize(xmlWriter, o, emptyNs);
return writer.ToString();
}
public static string Serializer<T>(T o)
{
var x = new XmlSerializer(typeof(T));
var writer = new StringWriter();
var xmlWriter = XmlWriter.Create(writer, new XmlWriterSettings { OmitXmlDeclaration = true });
x.Serialize(xmlWriter, o, new XmlSerializerNamespaces( new[] { XmlQualifiedName.Empty } ));
return writer.ToString();
}
and two deserializer method
public static T Deserializer<T>(string objectData)
{
var serializer = new XmlSerializer(typeof(T));
T result;
using (TextReader reader = new StringReader(objectData))
{
result =(T) serializer.Deserialize(reader);
}
return result;
}
public static object Deserializer(object o, string filename)
{
object retVal;
var ser = new XmlSerializer(o.GetType());
using (var reader = XmlReader.Create(filename))
{
retVal = ser.Deserialize(reader);
}
return retVal;
}
I have run different load tests in both of serializer methods, and all of them shown that Serializer<T>(T o) works slower than Serializer(object o), which in my opinion must be reverse since typeof() is faster and the type is known unlike object. I would like to know about your opinions first ?
and second, the serializer and deserializer methods used in another method named
public static TResponse SendRequest <TRequest,TResponse>(TRequest rq, Uri requestUri)
which is responsible to send the request to web server and get the response back, is there anyway to make it more efficient ?
I wrote the following code and I didn't notice any significant difference. Though, serializing through generics is slightly faster. Here is the code:
public class TestData {
public string Name { get; set; }
public string FullName { get; set; }
public string Address { get; set; }
public int PostalCode { get; set; }
public TestData() {
}
public TestData(string name, string fullName, string address, int postalCode) {
Name = name;
FullName = fullName;
Address = address;
PostalCode = postalCode;
}
}
public static class Program
{
public static string Serializer(object o)
{
var x = new XmlSerializer(o.GetType());
var writer = new StringWriter();
var xmlWriter = XmlWriter.Create(writer, new XmlWriterSettings { OmitXmlDeclaration = true });
var emptyNs = new XmlSerializerNamespaces(new[] { XmlQualifiedName.Empty });
x.Serialize(xmlWriter, o, emptyNs);
return writer.ToString();
}
public static string Serializer<T>(T o)
{
var x = new XmlSerializer(typeof(T));
var writer = new StringWriter();
var xmlWriter = XmlWriter.Create(writer, new XmlWriterSettings { OmitXmlDeclaration = true });
x.Serialize(xmlWriter, o, new XmlSerializerNamespaces(new[] { XmlQualifiedName.Empty }));
return writer.ToString();
}
public static void Main(string[] args) {
Random rand = new Random();
const int numberOfCycles = 1000000;
Stopwatch watch = new Stopwatch();
watch.Start();
for (int i = 0; i < numberOfCycles; i++) {
object data = new TestData("", "", "", rand.Next());
Serializer(data);
}
watch.Stop();
Console.WriteLine(string.Format("Through object:{0}", watch.ElapsedMilliseconds));
watch.Restart();
for (int i = 0; i < numberOfCycles; i++) {
Serializer(new TestData("", "", "", rand.Next()));
}
watch.Stop();
Console.WriteLine(string.Format("Through generic:{0}", watch.ElapsedMilliseconds));
Console.ReadLine();
}
}
Maybe it would be better to share with us a class you are trying to serialize/deserialize and share the code by which you made your estimations of executing time of serializing methods.

Serialize JSON from List<T> and Show Values

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"}]

Deserialize JSON string to c# object

My Application is in Asp.Net MVC3 coded in C#.
This is what my requirement is. I want an object which is in the following format.This object should be achieved when I deserialize the Json string.
var obj1 = new { arg1=1,arg2=2 };
After using the below code:
string str = "{\"Arg1\":\"Arg1Value\",\"Arg2\":\"Arg2Value\"}";
JavaScriptSerializer serializer1 = new JavaScriptSerializer();
object obje = serializer1.Deserialize<object>(str);
The object what i get i.e obje does not acts as obj1
Here, in this example my JSON string is static, but actually JSON string is going to be dynamically generated runtime, so i won't be able get Arg1 and Arg2 all the time.
I think the JavaScriptSerializer does not create a dynamic object.
So you should define the class first:
class MyObj {
public int arg1 {get;set;}
public int arg2 {get;set;}
}
And deserialize that instead of object:
serializer.Deserialize<MyObj>(str);
Not testet, please try.
Use this code:
var result=JsonConvert.DeserializeObject<List<yourObj>>(jsonString);
I believe you are looking for this:
string str = "{\"Arg1\":\"Arg1Value\",\"Arg2\":\"Arg2Value\"}";
JavaScriptSerializer serializer1 = new JavaScriptSerializer();
object obje = serializer1.Deserialize(str, obj1.GetType());
This may be useful:
var serializer = new JavaScriptSerializer();
dynamic jsonObject = serializer.Deserialize<dynamic>(json);
Where "json" is the string that contains the JSON values. Then to retrieve the values from the jsonObject you may use
myProperty = Convert.MyPropertyType(jsonObject["myProperty"]);
Changing MyPropertyType to the proper type (ToInt32, ToString, ToBoolean, etc).
solution :
public Response Get(string jsonData) {
var json = JsonConvert.DeserializeObject<modelname>(jsonData);
var data = StoredProcedure.procedureName(json.Parameter, json.Parameter, json.Parameter, json.Parameter);
return data;
}
model:
public class modelname {
public long parameter{ get; set; }
public int parameter{ get; set; }
public int parameter{ get; set; }
public string parameter{ get; set; }
}
Same problem happened to me. So if the service returns the response as a JSON string you have to deserialize the string first, then you will be able to deserialize the object type from it properly:
string json= string.Empty;
using (var streamReader = new StreamReader(response.GetResponseStream(), true))
{
json= new JavaScriptSerializer().Deserialize<string>(streamReader.ReadToEnd());
}
//To deserialize to your object type...
MyType myType;
using (var memoryStream = new MemoryStream())
{
byte[] jsonBytes = Encoding.UTF8.GetBytes(#json);
memoryStream.Write(jsonBytes, 0, jsonBytes.Length);
memoryStream.Seek(0, SeekOrigin.Begin);
using (var jsonReader = JsonReaderWriterFactory.CreateJsonReader(memoryStream, Encoding.UTF8, XmlDictionaryReaderQuotas.Max, null))
{
var serializer = new DataContractJsonSerializer(typeof(MyType));
myType = (MyType)serializer.ReadObject(jsonReader);
}
}
4 Sure it will work.... ;)

Categories

Resources