Json array deserialize from DataContractJsonSerializer method to JsonConvert(newton.json)? - c#

I need to deserialize json array from web api (httpclient). I have DataContractJsonSerializer but no use i need to use JsonConvert, I don't know how to do this. My code:
{
[DataContract]
public class JsonDataContractObject
{
public string ToJson()
{
DataContractJsonSerializer ser = new DataContractJsonSerializer(this.GetType());
Stream s = new MemoryStream();
ser.WriteObject(s, this);
s.Position = 0;
StreamReader sr = new StreamReader(s);
return sr.ReadToEnd();
}
}
}
How to change DataContractJsonSerializer to JsonConvert(newton.json)?.

This is how to quickly serialise an object to json string
JsonConvert.SerializeObject(this);
For more info see https://www.newtonsoft.com/json/help/html/SerializingJSON.htm

Related

Unable to deserialize Json using DataContractJsonSerializer

My model:
internal class Order
{
internal string OrderId;
internal string ShippingId;
internal Date OrderDate;
internal double Amount;
}
My method that uses DataContractJsonSerializer :
Order GetOrder(string json)
{
Order obj;
using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(json)))
{
DataContractJsonSerializer deserializer = new DataContractJsonSerializer(typeof(Order));
obj = (Order) deserializer.ReadObject(ms);
}
return obj;
}
But its not able to deserialize it? I cant understand why its giving me exception always!

How to serialize/deserialize PictureBox

[Serializable]
class GameObject : PictureBox
{
public bool Solid;
public bool Selected;
}
Is there any way to serialize BackColor, Size, Location etc...?
For temporary small type of objects I prefer to use structures, although you can use classes as per your needs. You can serialize and de-serialize objects using these helper methods.
public static string Serialize<T>(T objectToSerialize)
{
XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
StringWriter textWriter = new StringWriter();
xmlSerializer.Serialize(textWriter, objectToSerialize);
return textWriter.ToString();
}
public static T Deserialize<T>(string stringToDeserialize)
{
XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
StringReader textReader = new StringReader(stringToDeserialize);
return (T)xmlSerializer.Deserialize(textReader);
}
How to Serialize object-to-string:
MyStructure myObject = GetPictureBoxObject();
string pbSerializedString = Serialize<MyStructure>(myObject);
How to DeSerialize string-to-object:
string str = GetStringToDeserialize();
MyStructure myObject = Deserialize<MyStructure>(str);

How do i get a list of json objects from json file

I could serialize one node of json file like below
using (JsonTextReader jsonReader = new JsonTextReader(file))
{
deserializedJson = eerializer.Deserialize<Person>(jsonReader);
}
JsonNRadio is autogenerated class with json file.
Now my json file has multiple json objects.
so, for this i created a class called Persons
public class Persons
{
private Person[] person;
public Person[] person
{
get
{
return this.person;
}
set
{
this.person= value;
}
}
}
public partial class Person
{
public string id { get; set; }
public string name { get; set; }
}
Now I should get a aaray of json objects but when I am trying with below code, I am getting only the first node.
JsonSerializer serializer = new JsonSerializer();
using (StreamReader file = File.OpenText(#"D:\\Sample.json"))
// deserializedXml = serialized.Deserialize(xmlStream);
using (JsonTextReader jsonReader = new JsonTextReader(file))
{
Persons deserializedXml = serializer.Deserialize<Persons> (jsonReader);
}
And Person is object is coming null.
Could anybody help with an example or how to get a list of json objects.
For receiving json data with your Persons class above, your json file have to look like this:
{"Person":[{"id":"6397486515343190","name":"Henry"},{"id":"6397486515343192","name":"Paul"}]}
But since you have no influence on the design of the json data, you could simply deserialize it into a list of Person:
using (JsonTextReader jsonReader = new JsonTextReader(file))
{
var deserializedXml = serializer.Deserialize<List<Person>> (jsonReader);
}
This should work for you.
For editing your json string before deserialize it because of the missing "[" and "]". You can use something like that if you don't want to add much more new code:
using (JsonTextReader jsonReader = new JsonTextReader(file))
{
var json = "[" + jsonReader.Value.ToString() + "]";
var deserializedXml = JsonConvert.DeserializeObject<List<Person>>(json);
}
Or you can read the file with a normal FileReader into a string object and adding the "[", "]" at the beginning and ending.

Object de-serializing from base64 in C#

I have a class as so
[Serializable]
public class ExternalAccount
{
public string Name { get;set;}
}
I have converted this to JSON like so
{\"Name\":\"XYZ\"}
I have then base64 encoded the JSON string
I then send across the wire to a web api service
I receive the base64 encoded string and now need to de-serialize it back to the original object as above (ExternalAccount) so i firstly do a
byte[] byteArray = Convert.FromBase64String(base64EncodedExternalAccount);
What is the next step?
I have tried the below but this returns null...
using (MemoryStream memoryStream = new MemoryStream(byteArrayToConvert))
{
BinaryFormatter binaryFormatter = new BinaryFormatter();
// set memory stream position to starting point
memoryStream.Position = 0;
// Deserializes a stream into an object graph and return as a object.
return binaryFormatter.Deserialize(memoryStream) as ExternalAccount;
}
Any pointers/tips greatly appreciated.
You can try converting the byte array back to string (it will be the same JSON you sent), then deserialize to the ExternalAccount object. Using the Newtonsoft JSON library the following sample correctly displays "Someone" on the console:
class Program
{
static void Main(string[] args)
{
var account = new ExternalAccount() { Name = "Someone" };
string json = JsonConvert.SerializeObject(account);
string base64EncodedExternalAccount = Convert.ToBase64String(Encoding.UTF8.GetBytes(json));
byte[] byteArray = Convert.FromBase64String(base64EncodedExternalAccount);
string jsonBack = Encoding.UTF8.GetString(byteArray);
var accountBack = JsonConvert.DeserializeObject<ExternalAccount>(jsonBack);
Console.WriteLine(accountBack.Name);
Console.ReadLine();
}
}
[Serializable]
public class ExternalAccount
{
public string Name { get; set; }
}
you need to extract string from the bytes you recieve.
byte[] byteArray = Convert.FromBase64String(base64EncodedExternalAccount);
string AccountInfo = System.Text.Encoding.UTF8.GetString(byteArray );
As expected, you will get {\"Name\":\"XYZ\"} in your AccountInfo string. Now you need to Deserialize. you can use the same model, ExternalAccount. you may do something like:
ExnternalAccount model = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize<ExnternalAccount>(AccountInfo );

Using WebClient for JSON Serialization?

I know you can deserialize a JSON object from an HttpWebResponse using the WebClient.DownloadString() but what about the other way around? I've looked at the MSDN pages and I don't know if you can serialize to JSON objects or not, anyone know?
I think you may just have to serialize the object into JSON before using the WebClient instance. Hope this helps
var url = "...";
var json = JsonHelper.ToJson(myObject);
var response = PostJson(url, json);
Here's an example of sending JSON data from the WebClient class:
public static string PostJson(string url, string data)
{
var bytes = Encoding.Default.GetBytes(data);
using (var client = new WebClient())
{
client.Headers.Add("Content-Type", "application/json");
var response = client.UploadData(url, "POST", bytes);
return Encoding.Default.GetString(response);
}
}
Here is a simple helper class that uses the DataContractJsonSerializer class to serialize / deserialize object to and from JSON.
public static class JsonHelper
{
public static string ToJson<T>(T instance)
{
var serializer = new DataContractJsonSerializer(typeof(T));
using (var tempStream = new MemoryStream())
{
serializer.WriteObject(tempStream, instance);
return Encoding.Default.GetString(tempStream.ToArray());
}
}
public static T FromJson<T>(string json)
{
var serializer = new DataContractJsonSerializer(typeof(T));
using (var tempStream = new MemoryStream(Encoding.Unicode.GetBytes(json)))
{
return (T)serializer.ReadObject(tempStream);
}
}
}
I use :
var json = new JavaScriptSerializer().Serialize(yourObject);

Categories