I'm trying to deserialize a JSON object into an Object with some "object" attribute that may be different each time. I have a serializer/deserializer function that works fine when using simple variable types or defined ones.
I tried to cast the object into the correct class, tried to get the object as dynamic, etc. However, I always get an exception: "Object Reference not established..."
Deserialization func:
public static T deserializeJSON<T>(string json)
{
T obj = Activator.CreateInstance<T>();
using (MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(json)))
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType($
obj = (T)serializer.ReadObject(ms);
}
return obj;
}
Example object:
[DataContract]
class Client
{
[DataMember] private string name;
[DataMember] private string address;
[DataMember] private string bio;
[DataMember] private object specific; //WHERE SPECIFIC MAY BE ANY OTHER OBJECT THAT I CAST AFTER DESERIALIZATION
}
Example object2:
[DataContract]
class Server
{
[DataMember] private string name;
[DataMember] private int value;
}
The specific attribute may be any other object. Imagine "specific" attribute is a Server type object; The deserialization function loads all attributes well instead of specific that is loaded as an object, but cannot convert it to Server.
PD: At deserialization moment, I know what class type is the "specific" attribute.
Thanks!
using latest json.net you can use
dynamic data = Json.Decode(json);
or
dynamic data = JObject.Parse(json);
and can access data with following code :
data.Date;
data.Items.Count;
data.Items[0].Name;
data.Items[0].Price;
data.Items[1].Name;
Related
While trying to de-serialize a complex JSON object (JIRA issue) into an object containing a dictionary of type string-Field I've hit a bit of a bump.
While I can de-serialize various pre-determined object types (standard), I'm having a bit of a harder time with the custom fields, which could be of various types (they all begin with customfield_ followed by a set of numbers).
The custom fields can be floats, strings, booleans, objects and arrays of objects. The latter of these is causing me issues since I can't seem to determine what the object is before I de-serialize it.
I've searched for a way to perhaps "peek" at the data in the object before de-serializing as one of the fields contains information specific to it's type. This is all so I can determine the type of the object and tell Json.Net what to de-serialize it as.
I've considered parsing the JSON string before serialization to get the information, or maybe just when hitting this particular case, but maybe there is a better way?
Thanks in advance for any advice on this.
You can deserialize to an object with Json.Net. Here's a quick and dirty example:
using System;
using Newtonsoft.Json;
namespace Sandbox
{
class Program
{
private static void Main(string[] args)
{
var nestDto = new Dto
{
customfield_1 = 20,
customfield_2 = "Test2"
};
var dto = new Dto
{
customfield_1 = 10,
customfield_3 = new[] { nestDto },
customfield_2 = "Test"
};
var jsonString = JsonConvert.SerializeObject(dto);
Console.WriteLine(jsonString);
var fromJsonString = JsonConvert.DeserializeObject<Dto>(jsonString);
Console.WriteLine(fromJsonString.customfield_3[0].customfield_2); //Outputs Test2
Console.ReadKey();
}
}
class Dto
{
public int customfield_1 { get; set; }
public string customfield_2 { get; set; }
public Dto[] customfield_3 { get; set; }
}
}
Instead of peaking, you can deserialize as the same type as JSON.net uses for ExtensionData explicitly. For example:
if (reader.TokenType == JsonToken.StartArray)
{
var values = serializer.Deserialize<List<Dictionary<string, JToken>>>(reader);
objectContainer = ClassifyAndReturn(values);
}
private ObjectType ClassifyAndReturn(List<Dictionary<string, JToken>> values)
{
if (values.First().ContainsKey("self"))
{
string self = values.First()["self"].Value<string>();
if (self.Contains("customFieldOption"))
//... Then go into a series of if else cases to determine the object.
The representation of the objects are given as a Dictionary of string to JToken, which can then easily be checked and assigned manually or in some cases automatically deserialized (in the case one of the fields is another object).
Here is what an object constructor could look like:
internal myobject(Dictionary<string, JToken> source)
{
Self = source["self"].Value<string>();
Id = source["id"].Value<string>();
Value = source["value"].Value<string>();
}
I'm recieving a JSON object that looks like the example below.
{
"name1":{"name1a":"value1a","name1b":"value1b"},
"name2":{"name2a":"value2a","name2b":"value2b"}
}
I've set up a data contract for it (since I only need to access a single data field at the moment) like this.
[DataContract]
public class MyThingy
{
[DataMember(Name="name1b")]
public string Name1b { get; set; }
public MyThingy() { }
public MyThingy(String name1b)
{
Name1b = name1b;
}
}
When I've serialized the object, I try to print it out (which works, since I'm getting a string description of the class) and them the field Name1b. The last part doesn't work and I'm getting null there. My guess is that I must have mapped the data contract wrongly but I can't see how to correct it.
How should the MyThingy class be declared?
My JSON object is fetched as described in this post.
I would use JavaScriptSerializer here,
string json = #"{
""name1"":{""name1a"":""value1a"",""name1b"":""value1b""},
""name2"":{""name2a"":""value2a"",""name2b"":""value2b""}
}";
var obj = new JavaScriptSerializer()
.Deserialize<Dictionary<string, Dictionary<string, string>>>(json);
Console.WriteLine(obj["name1"]["name1b"]);
You can also use Json.Net and dynamic together
dynamic obj = JsonConvert.DeserializeObject(json);
Console.WriteLine(obj.name1.name1b);
I have an object I want to deserialize, which is declared as struct in an external library (which is marked as Serializable).However, Json.net is not able to deserialize this object. Serialization is fine, but deserialize doesn't work. I already tried to change struct to class but it didn't help. Do I need to put something special in the JsonSerializerSettings or something else, or isn't it supported? I already tried several of the parameters there, like TypeNameHandling and TypeNameAssemblyFormat, but it didn't work.
As asked, some code, this is declared in external library:
[Serializable]
public struct BarEntry
{
public RegistryValueKind One;
public string Two;
public string Three;
public string Four;
public object Five;
}
[Serializable]
public struct FooEntry
{
public string One;
public string Two;
}
Serialized in own project as:
Stream stream = System.IO.File.Open(fileName, FileMode.Create);
string json = JsonConvert.SerializeObject(entry, Formatting.None, new JsonSerializerSettings { PreserveReferencesHandling = PreserveReferencesHandling.Objects });
StreamWriter streamWriter = new StreamWriter(stream);
streamWriter.Write(json);
streamWriter.Flush();
stream.Close();
Deserialized in own project as:
StreamReader streamReader = new StreamReader(input);
string json = streamReader.ReadToEnd();
object returnObject = JsonConvert.DeserializeObject<T>(json);
input.Close();
return returnObject;
Everything inside own project works fine with this code, but from external library it is not able to deserialize the objects (From both BarEntry and FooEntry).
Also BarEntry and FooEntry are both stored in the same property in their storage object:
public object Entry { get; set; }
You must send exact type to JsonConvert.DeserializeObject, otherwise there is no way to create right object that will have needed properties to deserialize to from json string. So load this type from external assembly and send it to Json.NET. Something like this :
Assembly assembly = Assembly.LoadFile("ExternalAssembly.dll");
Type barEntryType = assembly.GetType("BarEntry");
var returnObject = JsonConvert.DeserializeObject(json, barEntryType);
or reference the external assembly and simply do this :
BarEntry returnObject = JsonConvert.DeserializeObject<BarEntry>(json)
I'm using the DataContractJsonSerializer to deserialize objects from an external service. In most cases, this has worked great for me. However, there is one case where I need to deserialize JSON that contains a list of objects that all inherit from the same base class, but there are many different types of objects in that list.
I know that it can be done easily by including a list of known types in the serializer's constructor, but I don't have access to the code that generated this JSON service. The types that I'm using will be different from the types used in the service (mostly just the class name and namespace will be different). In other words, the classes that the data was serialized with will not be the same classes that I'll use to deserialize it even though they'll be very similar.
With the XML DataContractSerializer, I can pass in a DataContractResolver to map the services types to my own types, but there is no such constructor for the DataContractJsonSerializer. Is there any way to do this? The only options that I've been able to find are: write my own deserializer, or use Microsoft's JsonObject that isn't tested and "should not be used in production environments."
Here is an example:
[DataContract]
public class Person
{
[DataMember]
public string Name { get; set; }
}
[DataContract]
public class Student : Person
{
[DataMember]
public int StudentId { get; set; }
}
class Program
{
static void Main(string[] args)
{
var jsonStr = "[{\"__type\":\"Student:#UnknownProject\",\"Name\":\"John Smith\",\"StudentId\":1},{\"Name\":\"James Adams\"}]";
using (var stream = new MemoryStream())
{
var writer = new StreamWriter(stream);
writer.Write(jsonStr);
writer.Flush();
stream.Position = 0;
var s = new DataContractJsonSerializer(typeof(List<Person>), new Type[] { typeof(Student), typeof(Person) });
// Crashes on this line with the error below
var personList = (List<Person>)s.ReadObject(stream);
}
}
}
Here is the error mentioned in the comment above:
Element ':item' contains data from a type that maps to the name
'http://schemas.datacontract.org/2004/07/UnknownProject:Student'. The
deserializer has no knowledge of any type that maps to this name. Consider using
a DataContractResolver or add the type corresponding to 'Student' to the list of
known types - for example, by using the KnownTypeAttribute attribute or by adding
it to the list of known types passed to DataContractSerializer.
I found the answer. It was very simple. I just needed to update my DataContract attribute to specify which namespace (you can also specify a different name) they map to in the source JSON like this:
[DataContract(Namespace = "http://schemas.datacontract.org/2004/07/UnknownProject")]
public class Person
{
[DataMember]
public string Name { get; set; }
}
[DataContract(Namespace = "http://schemas.datacontract.org/2004/07/UnknownProject"]
public class Student : Person
{
[DataMember]
public int StudentId { get; set; }
}
That JsonObject was a sample for .NET 3.5. There is a project in codeplex - http://wcf.codeplex.com - which has a tested implementation of the JsonValue/JsonObject/JsonArray/JsonPrimitive classes, including source code and unit tests. With that you can parse "untyped" JSON. Another well-used JSON framework is the JSON.NET at http://json.codeplex.com.
You may create a DTO before serializing.
I use a class like: (pseudo code)
class JsonDto
string Content {get;set;}
string Type {get;set;}
ctor(object) => sets Content & Type Properties
static JsonDto FromJson(string) // => Reads a Serialized JsonDto
// and sets Content+Type Properties
string ToJson() // => serializes itself into a json string
object Deserialize() // => deserializes the wrapped object to its saved Type
// using Content+Type properties
T Deserialize<T>() // deserializes the object as above and tries to cast to T
Using the JsonDto you can easily serialize arbitrary objects to JSON and deserialize them to their common base type because the deserializer will always know the original type and returns an type of object reference which will be casted if you use the generic Deserialize<T> method.
One caveat: If you set the Type property you should use the AssemblyQualifiedName of the type, however without the version attribute (ex: MyCompany.SomeNamespace.MyType, MyCompany.SomeAssembly). If you just use the AssemblyQualifiedName property of the Type class you will end up with errors if your assembly version changes.
I implemented a JsonDtoCollection the same way, which derives from List<JsonDto> and provides methods to handle collections of objects.
class JsonDtoCollection : List<JsonDto>
ctor(List<T>) => wraps all items of the list and adds them to itself
static JsonDtoCollection FromJson(string) // => Reads a collection of serialized
// JsonDtos and deserializes them,
// returning a Collection
string ToJson() // => serializes itself into a json string
List<object> Deserialize() // => deserializes the wrapped objects using
// JsonDto.Deserialize
List<T> Deserialize<T>() // deserializes the as above and tries to cast to T
I have an object in Javascript that looks like this
function MyObject(){
this.name="";
this.id=0;
this.....
}
I then stringify an array of those objects and send it to an ASP.Net web service.
At the webservice I want to unserialize the JSON string so I can deal with the data easily in C#. Then, I want to send an array of objects of the same Javascript type(same field names and everything) back to the client. The thing I'm not understanding is how to serialize say this class:
class MyObject{
public string Name;
public int ID;
}
so that the JSON is the same as the above javascript object. And also how to unserialize into the C# MyObject class.
How would I do this easily? I am using Netwonsoft.Json.
Is there some way to turn a JSON string into a List or Array of an object?
with json.net you can use the JsonPropertyAttribute to give your serialized properties a custom name:
class MyObject{
[JsonProperty(PropertyName = "name")]
public string Name;
[JsonProperty(PropertyName = "id")]
public int ID;
}
you can then serialize your object into a List<> like so:
var list = new List<MyObject>();
var o = new MyObject();
list.Add(o);
var json = JsonConvert.SerializeObject(list);
and deserialize:
// json would look like this "[{ "name":"", "id":0 }]"
var list = JsonConvert.DeserializeObject<List<MyObject>>(json);
One thing the WebMethod gives you back is a "d" wrapper which I battled with for hours to get around. My solution with the Newtonsoft/JSON.NET library is below. There might be an easier way to do this I'd be interested to know.
public class JsonContainer
{
public object d { get; set; }
}
public T Deserialize<T>(string json)
{
JsonSerializer serializer = new JsonSerializer();
JsonContainer container = (JsonContainer)serializer.Deserialize(new StringReader(json), typeof(JsonContainer));
json = container.d.ToString();
return (T)serializer.Deserialize(new StringReader(json), typeof(T));
}
You can try the DataContractJsonSerializer Rick Strahl Has a fairly good example.
You tell the serializer the type that you are serializing to and you can decorate the class properties telling them to expect a different name.
As an example:
class MyObject{
[DataMember(name="name")]
public string Name;
[DataMember(name="id")]
public int ID;
}
EDIT: Use
using (MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(jsonString)))
{
ser = new DataContractJsonSerializer(typeof(MyObject));
MyObject obj = ser.ReadObject(ms) as MyObject;
int myObjID = obj.ID;
string myObjName = obj.Name;
}