How to use Deserialization code in android? - c#

This is C# code, please convert it to Android code.
T obj = Activator.CreateInstance<T>();
MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(json));
System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(obj.GetType());
obj = (T)serializer.ReadObject(ms);

I don't know c#, But for JSON serialization in android you can use GSON,download GSON library and import it in your project. Go throw the following link for more info. https://sites.google.com/site/gson/gson-user-guide#TOC-Collections-Examples

Related

Error while deserializing the JSON of float array with Newtonsoft.Json in C# console app

I'm using Newtonsoft.Json library and i can't acomplish a rather simple task:
Serialize an array of floats and then deserialize the same file.
My console aplication looks like this:
var x_train = new float[3];
x_train[0] = 0.23f;
x_train[1] = 11.23f;
x_train[2] = 22.22f;
string output = JsonConvert.SerializeObject(x_train);
JsonSerializer serializer = new JsonSerializer();
using (StreamWriter sw = new StreamWriter(_pathToSerializedObjects + "\\x_train.json"))
using (JsonWriter writer = new JsonTextWriter(sw))
{
serializer.Serialize(writer, output);
}
//The file is serialized correctly, now the problem is this block of code:
// deserialize JSON directly from a file
using (StreamReader file = File.OpenText(_pathToSerializedObjects + "\\x_train.json"))
{
JsonSerializer serializer2 = new JsonSerializer();
var dx = (float[])serializer.Deserialize(file, typeof(float[]));
Console.WriteLine(dx[0]);
Console.WriteLine(dx[1]);
Console.WriteLine(dx[2]);
}
The line :
"var dx = (float[])serializer.Deserialize(file, typeof(float[]));"
Throws:
Newtonsoft.Json.JsonSerializationException: 'Error converting value "[0.23,11.23,22.22]" to type 'System.Single[]'. Path '', line 1, position 20.'
I believe that i'm missusing the Newtonsoft.Json library but i can't find examples
of serializing primitives.
Environment:
.net Core 3.1 (Console app)
Newtonsoft.Json 12.0.3
Thanks in advance.
You are serializing twice. output contains serialized array and you are serializing that string to a file. You don't need JSON serializer to write text that already represents JSON value. You can use File.WriteAllText for that.

Create JSON object from Multiline textbox windows phone

In my windows phone app, I'm in a need of creating a JSON object dynamically. i.e. I will know the property names only during run time. Also the property values can contain multiple lines.
Previously when I had to include multiple lines in a JSON object without any problem I used the following.
MemoryStream ms = new MemoryStream();
DataContractJsonSerializer ser = new DataContractJsonSerializer(obj.GetType());
ser.WriteObject(ms, obj);
using (StreamReader sr = new StreamReader(ms))
{
ms.Position = 0;
input = sr.ReadToEnd();
}
return input;
This worked very fine. But in order to use I should've known the class before hand. Unfortunately it is not possible.
Can anyone help me with any work around ?
Thank you.
DataContractJsonSerializer does not support such things.
You should try, for instance, Json.net.

Get JSON from website then parse it in C#

So there is 1 website from where I need to get this JSON data.
The link is direct (I am using the website's API )
THe problem is, the file is HUGE!. Tens of Thousands of Lines.. Even more..
I have visual studio 2013 and what I need to do is download that JSON data in a callback and then parse it to get a specific value. I am using Newtonsoft.JSON to parse it and here is what I have thought will be able to parse it
var obj = JsonConvert.DeserializeObject<JContainer>(jsonText);
var value = (int)obj["response"]["prices"]["5021"]["6"]["0"]["current"]["value"];
The problem is, how do I download all of that data and convert it into C# classes? Is there another way?
Thanks a lot.
EDIT: If not JSON, I have option to download it in JSONP and VDF format
Here is the link of the JSON data - http://backpack.tf/api/IGetPrices/v3/?format=json&key=52f75dab4dd7b82f698b4568
I got it working by doing this
using (var webClient = new System.Net.WebClient())
{
var json = webClient.DownloadString("http://backpack.tf/api/IGetPrices/v3/?format=json&key=00a00aaa0aa0a00a000a0000");
Newtonsoft.Json.Linq.JObject o = Newtonsoft.Json.Linq.JObject.Parse(json);
var value = (int)o["response"]["prices"]["5021"]["6"]["0"]["current"]["value"];
Console.WriteLine(value);
}
Thanks for your help everybody!!
Try restsharp. It let you do something like
var prices = client.Execute<Prices>(request);
Where Prices is the class that matches the returned schema
Looking at the comment Brandon posted, he's right in principle, but you don't have to switch to Newtonsoft if you don't want. You just need to use a different JSON.NET API
var serializer = new JsonSerializer();
using (var stream = File.OpenRead("C:\\Users\\gweakliem\\Downloads\\sotest.js"))
{
using (StreamReader streamReader = new StreamReader(stream))
{
using (JsonReader reader = new JsonTextReader(streamReader))
{
var aThing = serializer.Deserialize<JContainer>(reader);
var aValue = (int) aThing["response"]["prices"]["5021"]["6"]["0"]["current"]["value"];
Console.WriteLine("Read a value " + aValue);
}
}
}
If you're concerned about blocking on this thread while reading, it looks like you're going to have to write some code. I don't see awaitable methods on JsonTextReader or JsonSerializer, so I expect that those methods will block.
Now if you want to turn this into objects, here's a couple other SO posts:
deserialize json into .net object using json.net
dynamic JContainer (JSON.NET) & Iterate over properties at runtime
Or this post covers a bunch of deserialization options.

Portable Object Format (POF) serialization in .NET

I have a class called MyClass and pof configuration for this type (my-pof-config.xml).
I need to serialize an instance of MyType and then send it via JMS.
In Coherence Java API, there is ExternalizableHelper.toByteArray/fromByteArray. How can I do POF (Portable Object Format) serialization and deserialization in C#?
Thank you.
In .Net you have Tangosol.Util.SerializationHelper which does the same as Java's ExternalizableHelper; something like this...
serialize:
ConfigrablePofContext serializer = new ConfigurablePofContext("...config file name...");
Binary binary = SerializationHelper.ToBinary(objectToSerialize, serializer);
byte[] bytes = binary.ToByteArray();
deserialize
ConfigrablePofContext serializer = new ConfigurablePofContext("...config file name...");
Binary binary = new Binary(byteArray);
Object deserializedValue = SerializationHelper.FromBinary(binary, serializer);

How to handle JSON in C#?

Is there an easy/elegant parser for dealing with JSON in C#? How about actually serializing/deserializing into C# objects?
JSON.Net is a pretty good library
var jss = new JavaScriptSerializer();
var data = jss.Deserialize<dynamic>(jsonString);
Don't forget to reference "System.Web.Extensions"
See
http://msdn.microsoft.com/en-us/library/system.runtime.serialization.json.datacontractjsonserializer.aspx
Basically you can use the 'data contract' model (that's often used for WCF XML serialization) for JSON as well. It's pretty quick and easy to use standalone for little tasks, I have found.
Also check out this sample:
http://msdn.microsoft.com/en-us/library/bb943471.aspx
There's the DataContractJsonSerializer class.
Deserialize:
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(MyObject));
Stream s = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(json_string));
MyObject obj = ser.ReadObject(s) as MyObject;
Serialize:
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(MyObject));
Stream s = new MemoryStream();
MyObject obj = new MyObject { .. set properties .. };
ser.WriteObject(s, obj);
s.Seek( SeekOrigin.Begin );
var reader = new StreamReader(s);
string json_string = reader.ReadToEnd();
DataContractJsonSerializer for serializing to/from objects.
In Silverlight 3, there's System.Json (http://msdn.microsoft.com/en-us/library/system.json(VS.95).aspx), very handy.

Categories