JSON.net deserializes a reference to null - c#

I have a C# application centered around objects called ProductParts, one Part can contain one or more child ProductParts. However, a Part can also contain references to other Parts in an indirect manner.
class ProductPart
{
List<ProductPart> ProductParts;
ProductPart MaterialReference { get; set; }
ProductPart ColorReference { get; set; }
ProductPart ActiveStateReference { get; set; }
}
I use JSON.net to save/load these Parts. However, I noticed an issue with certain references.
Here's a slimmed down JSON file example to demonstrate my problem.
{
"$id": "3",
"Name": "ProductName",
"ProductParts": {
"$id": "5",
"$values": [
{
"$id": "6",
"Name": "top",
"ProductParts": {
"$id": "8",
"Name": "bottom",
"$values": [
{
"$id": "9",
"MaterialReference": {
"$ref": "6"
},
"ColorReference": {
"$ref": "6"
},
"ActiveStateReference": {
"$ref": "6"
}
}
]
}
}
]
}
}
When I load a file like this into my application, the Reference fields are null. Is this because I've created an reference loop here? I tried to get JSON.net to throw an error in this case by using
ReferenceLoopHandling = ReferenceLoopHandling.Error
But to my surprise, that doesn't throw an error. Have I created a Datastructure that cannot be parsed?

You need to remove the circular reference in your class. Create a Mapping class structure like this to deserialize the Json
class ProductPart
{
[JsonProperty("$id")]
public int Id { get; set; }
public string Name { get; set; }
[JsonProperty("ProductParts")]
List<ProductPartsA> ProductPartsA;
}
class ProductPartsA
{
[JsonProperty("$id")]
public int Id { get; set; }
public string Name { get; set; }
[JsonProperty("ProductParts")]
List<ProductPartsB> ProductPartsB;
}
class ProductPartsB
{
[JsonProperty("$id")]
public int Id { get; set; }
public string Name { get; set; }
[JsonProperty("$values")]
List<Values> Values;
}
class Values
{
[JsonProperty("$id")]
public int Id { get; set; }
public Reference MaterialReference { get; set; }
public Reference ColorReference { get; set; }
public Reference ActiveStateReference { get; set; }
}
class Reference
{
[JsonProperty("$ref")]
public string Ref { get; set; }
}
Obviously this can be handled a little nicer with inheritance but you get the idea. You can then deserialize your json by simply:
var myClass = JsonConvert.DeserializeObject<ProductPart>(jsonstr);

Related

How to deserialise this nested json response and save the the array values with multiple Jobjects (in Unity)

I have little to no experience in JSON and I am stuck with a problem. Any help is appreciated.
I want to access specifically the names' values from the additionalInformation array.
JSON Response:
{
"statusCode": 200,
"version": 1,
"jsonData": [
{
"additionalInformation": [
{
"id": "XXX94XXXX9xxXx_xxxXXXX",
"name": "xxxx xxx x xxxxxxxx"
},
{
"id": "0xXXxcXxv5PQqT$6i2zLgV",
"name": "xxx xxxxxxxx"
},
{
"id": "11Krt_our2rPCPqJ_2fKZR",
"name": "xxx xxxxxxxx xx"
},
{
"id": "2jYw4IyBP8KuozM_ej7DGf",
"name": "xxxxxxx 1"
},
{
"id": "3B8O805wL1ufabHMz1Je3v",
"name": "xxxxxxx 2"
},
{
"id": "0FVKUYZkvFaxd_OQUiyPBZ",
"name": "xxxxxxx"
},
{
"id": "3O41QFd0573QQvFco5zUUP",
"name": "Xxxxxxxxx"
}
],
"type": 0
}
],
"errorMessages": [],
"warningMessages": [],
"informationMessages": []
}
Model:
public class CFunctions
{
public int statusCode { get; set; }
public int version { get; set; }
public List<PFunctions>[] jsonData { get; set; }
public List<string> errorMessages { get; set; }
public List<string> warningMessages { get; set; }
public List<string> informationMessages { get; set; }
/*public CFunctions()
{
jsonData = new List<PFunctions>();
}*/
}
[Serializable]
public class PFunctions
{
public List<PAdditionalInfo>[] additionalInformation { get; set; }
public int type { get; set; }
/*public PFunctions()
{
additionalInformation = new List<PAdditionalInfo>();
}*/
}
[Serializable]
public class PAdditionalInfo
{
public Guid id { get; set; }
public string name { get; set; }
}
Deserialisation
var request = UnityWebRequest.Get(baseurl);
var operation = request.SendWebRequest();
var jsonResponse = request.downloadHandler.text;
List<CFunctions>[] PFunctionsList = JsonConvert.DeserializeObject<List<CFunctions>[]>(jsonResponse);
Error:
Cannot deserialize the current JSON object into type 'System.Collections.Generic.List`1[CFunctions][]' because the type requires a JSON array to deserialize correctly.
To fix this error either change the JSON to a JSON array or change the deserialized type so that it is a normal .NET type that can be deserialized from a JSON object.
JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object.
Path 'statusCode', line 1, position 14.
UnityEngine.Debug:Log(Object)
What I tried
The error pertains even when I changed List<PAdditionalInfo> to List<PAdditionalInfo>[]
I am not sure how to use JsonObjectAttribute and if it is the best way.
You've declared an array of List<T> in the models, eg List<PAdditionalInfo>[]. The json represents single arrays, not nested. You can fix that by choosing one or the other (I decided to use List<> but array is valid too):
public class PFunctions
{
public List<PAdditionalInfo> additionalInformation { get; set; } // removed []
...
}
public class CFunctions
{
public int statusCode { get; set; }
public int version { get; set; }
public List<PFunctions> jsonData { get; set; } // removed []
...
}
The class you're deserializing to is incorrect. Deserialize to the correct type (which is CFunctions not List<CFunctions>[]):
CFunctions cFunctions = JsonConvert.DeserializeObject<CFunctions>(json);
the most efficient way to get an additional information is this one line code and you only need one class
List<AdditionalInformation> additionalInformation = JObject.Parse(json)
["jsonData"][0]["additionalInformation"].ToObject<List<AdditionalInformation>>();
class
public class AdditionalInformation
{
public string id { get; set; }
public string name { get; set; }
}

Deserialize json string to non public class members

I have class object like this:
public class CustomerCollection
{
public CustomerOrder CustOrder;
public CustomerCollection();
public CustomerCollection(CustomerItem[] custItems);
}
public class CustomerItem: IComparable
{
public string Note { get; set; }
public string NoteType { get; set; }
public int NoteTypeID { get; set; }
public int RecordID { get; set; }}
}
I am unable to deserialize my json as shown below to the CustomerItem class properties
{
"$id": "1",
"$type": "Server.CustomerCollection,Server.Common",
"custItems": {
"$id": "2",
"$type": "Server.CustomerItem[],Server.Common",
"$values": [
{
"$id": "3",
"$type": "Server.CustomerItem,Server.Common",
"note": "test note",
"NoteType ": "Test note type",
"NoteTypeID ": 123,
"RecordId ": 15678,
}
]
},
"CustOrder": 0
}
This my how I am deserializing:
retObject = JsonConvert.DeserializeObject<CustomerCollection>(response, Customer.GetDefualtSettings());
Only the custOrder gets the mapping done. CustomerItem properties are not mapping : actually CustomerItem[] array is empty.
Can someone give direction of the constructor handling here?

C# expando creating from JSON with validity check against Linked Classes model

I have the below rather simple build of classes, they represent a model, kindly note the linked classes (initialization included in appropriate instance constructors of each one):
public class DataClass
{
public int num { get; set; }
public string code { get; set; }
public PartClass part { get; set; }
public MemberClass member { get; set; }
public DataClass()
{
part = new PartClass();
member = new MemberClass();
}
}
public class PartClass
{
public int seriesNum { get; set; }
public string seriesCode { get; set; }
}
public class MemberClass
{
public int versionNum { get; set; }
public SideClass side { get; set; }
public MemberClass()
{ side = new SideClass(); }
}
public class SideClass : IMPropertyAsStringSettable
{
public string firstDetail { get; set; }
public string secondDetail { get; set; }
public bool include { get; set; }
public SideClass()
{ }
}
My problem is rather straightforward, however, the complication is on the implementation: I am creating a class dynamically, expando, and I read a JSON which, sometimes, is equivalent one-on-one with the DataClass hierarchy, like:
{
"num": "3",
"code": "some sort of string",
"part": {
"seriesNum": "3",
"seriesCode": "sample"
},
"member": {
"versionNum": "1.5",
"side": {
"firstDetail": "aFirst",
"secondDetail": "aSecond",
"include": "true"
}
}
}
and sometimes, only a few values are equivalent (being a sub-set of DataClass is not an error, if there is an unknown tag in JSON, this is an error - like for example, find "age": "18" in JSON, because DataClass does not contain anywhere an 'age' property etc.), like for example:
{
"num": "9",
"part": {
"seriesNum": "3",
},
"member": {
"versionNum": "1.5",
"side": {
"include": "true"
}
}
}
As said, I don't care if a property - or a whole tree of properties - is missing from the JSON compared to the DataClass.
My problem is, how to read the JSON and assign properties and values in expando, while checking that both the hierarchy as well as the property name are correct.
Could you help me please with this?

Loading JSON file gives serialization error

I have below JSON file,
[
{
"applicationConfig": {
"Name": "Name1",
"Site": "Site1"
},
"pathConfig": {
"SourcePath": "C:\\Temp\\Outgoing1",
"TargetPath": "C:\\Files"
},
"credentialConfig": {
"Username": "test1",
"password": "super1"
}
},
{
"applicationConfig": {
"Name": "Name2",
"Site": "Site2"
},
"pathConfig": {
"SourcePath": "C:\\Temp\\Outgoing2",
"TargetPath": "C:\\Files"
},
"credentialConfig": {
"Username": "test2",
"password": "super2"
}
}
]
And below are C# classes structure,
public class Configurations
{
public List<ApplicationConfig> ApplicationConfigs { get; set; }
public List<PathConfig> PathConfigs { get; set; }
public List<CredentialConfig> CredentialConfigs { get; set; }
}
public class ApplicationConfig
{
public string Name { get; set; }
public string Site { get; set; }
}
public class PathConfig
{
public string SourcePath { get; set; }
public string TargetPath { get; set; }
}
public class CredentialConfig
{
public string Username { get; set; }
public string password { get; set; }
}
Now trying to load JSON and getting below error,
using (var streamReader = new StreamReader(#"./Config.json"))
{
var X = JsonConvert.DeserializeObject<Configurations>(streamReader.ReadToEnd());
}
$exception {"Cannot deserialize the current JSON array (e.g. [1,2,3])
into type 'ConsoleApp8.Configurations' because the type requires a
JSON object (e.g. {\"name\":\"value\"}) to deserialize
correctly.\r\nTo 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 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.\r\nPath '', line 1, position
1."} Newtonsoft.Json.JsonSerializationException
What else I need to serialize?
Your JSON represents an array - although the closing [ should be a ]. But you're trying to serialize it into a single Configurations object. Additionally, you seem to be expecting separate arrays for the application configs, path configs and credential configs - whereas your JSON shows an array of objects, each of which has all three.
I suspect you want:
public class Configuration
{
[JsonProperty("applicationConfig")]
ApplicationConfig ApplicationConfig { get; set; }
[JsonProperty("pathConfig")]
PathConfig PathConfig { get; set; }
[JsonProperty("credentialConfig")]
CredentialConfig CredentialConfig { get; set; }
}
// Other classes as before, although preferably with the password property more conventionally named
Then use:
List<Configuration> configurations =
JsonConvert.DeserializeObject<List<Configuration>>(streamReader.ReadToEnd());
You'll then have a list of configuration objects, each of which will have the three "subconfiguration" parts.
Your JSON class definition is close but not quite. Moroever the last [ must be ]
JSON class definition is created wtih QuickType
public partial class Configuration
{
[JsonProperty("applicationConfig")]
public ApplicationConfig ApplicationConfig { get; set; }
[JsonProperty("pathConfig")]
public PathConfig PathConfig { get; set; }
[JsonProperty("credentialConfig")]
public CredentialConfig CredentialConfig { get; set; }
}
public partial class ApplicationConfig
{
[JsonProperty("Name")]
public string Name { get; set; }
[JsonProperty("Site")]
public string Site { get; set; }
}
public partial class CredentialConfig
{
[JsonProperty("Username")]
public string Username { get; set; }
[JsonProperty("password")]
public string Password { get; set; }
}
public partial class PathConfig
{
[JsonProperty("SourcePath")]
public string SourcePath { get; set; }
[JsonProperty("TargetPath")]
public string TargetPath { get; set; }
}
Finally you need to serialize with
var config_list = JsonConvert.DeserializeObject<List<Configuration>>(streamReader.ReadToEnd());
I think it is a typo, you are opening the square bracket instead of closing it in the JSON file.
[ {
"applicationConfig": {
"Name": "Name1",
"Site": "Site1"
},
"pathConfig": {
"SourcePath": "C:\Temp\Outgoing1",
"TargetPath": "C:\Files"
},
"credentialConfig": {
"Username": "test1",
"password": "super1"
} }, {
"applicationConfig": {
"Name": "Name2",
"Site": "Site2"
},
"pathConfig": {
"SourcePath": "C:\Temp\Outgoing2",
"TargetPath": "C:\Files"
},
"credentialConfig": {
"Username": "test2",
"password": "super2"
} } [ <-HERE

AJAX POST Complex JSON to MVC4 Controller

I have a complex JSON object that I'd like to pass to a MVC4 Controller route.
{
"name": "Test",
"description": "Description",
"questions": [
{
"id": "1",
"type": "1",
"text": "123",
"answers": [
{
"answer": "123",
"prerequisite": 0
},
{
"answer": "123",
"prerequisite": 0
}
],
"children": [
{
"id": "2",
"type": "2",
"text": "234",
"answers": [
{
"answer": "234",
"prerequisite": 0
},
{
"answer": "234",
"prerequisite": 0
}
],
"children": []
}
]
}
]
I have these ViewModels defined:
public class FormDataTransformContainer
{
public string name { get; set; }
public string description { get; set; }
public QuestionDataTransformContainer[] questions;
}
public class QuestionDataTransformContainer {
public int type { get; set; }
public string text { get; set; }
public AnswerDataTransformContainer[] answers { get; set; }
public QuestionDataTransformContainer[] children { get; set; }
}
public class AnswerDataTransformContainer {
public string answer { get; set; }
public int prerequisite { get; set; }
}
And this is the route I'm hitting:
[HttpPost]
public ActionResult Create(FormDataTransformContainer formData)
{
Currently, the name and description property on FormDataTransformContainer are set, but the questions array is null. I hoped that the Data Binding would figure it out, but I assume the tree nature of the data structure is a little complex for it. If I'm correct what is the best solution to this?
questions should be a property, not a field. I'd also change from arrays to IList<> (assuming your serialization library handles that well), because that's probably closer to what it should be, and lets you use a more generic interface instead of a specific implementation.
public class FormDataTransformContainer
{
public string name { get; set; }
public string description { get; set; }
public IList<QuestionDataTransformContainer> questions { get; set; }
}
public class QuestionDataTransformContainer {
public int type { get; set; }
public string text { get; set; }
public IList<AnswerDataTransformContainer> answers { get; set; }
public IList<QuestionDataTransformContainer> children { get; set; }
}
public class AnswerDataTransformContainer {
public string answer { get; set; }
public int prerequisite { get; set; }
}
I've tested this structure with Json.net (MVC4's default, I believe), and it works.
As #robert-harvey said, you should utilize libraries like JSON.NET that are already available to do the heavy lifting for you.
Pulled from the JSON.NET API docs:
If you create a string json that holds your json, you can read from it with new JsonTextReader(new StringReader(json))
I a similar problem, solved with the following code:
public class ExtendedController : Controller
{
public T TryCreateModelFromJson<T>(string requestFormKey)
{
if (!this.Request.Form.AllKeys.Contains(requestFormKey))
{
throw new ArgumentException("Request form doesn't contain provided key.");
}
return
JsonConvert.DeserializeObject<T>(
this.Request.Form[requestFormKey]);
}
}
And usage:
[HttpPost]
[ActionName("EditAjax")]
public ActionResult EditAjaxPOST()
{
try
{
var viewModel =
this.TryCreateModelFromJson<MyModel>(
"viewModel");
this.EditFromModel(viewModel);
return
this.JsonResponse(
this.T("Model updated successfuly."),
true);
}
catch (Exception ex)
{
this.Logger.Error(ex, "Error while updating model.");
return this.JsonResponse(this.T("Error"), false);
}
}
Called from JS:
function saveViewModel() {
$.post(
'#Url.Action("EditAjax")',
{
__RequestVerificationToken: '#Html.AntiForgeryTokenValueOrchard()',
viewModel: ko.mapping.toJSON(viewModel)
},
function (data) {
// response
});
}
Used additional library for deserializing/serializing JSON: http://www.nuget.org/packages/Newtonsoft.Json

Categories