0

I'm using a C# app where data classes I use look like this :

class Node {
  public string name;
  public int id;
  public Node parent;
  public Node[] children;
  public Data data;
}

class Community {
  public Node[] nodes;
}

class Data {
  public string info;
  public int value;
}

I declare in javascript these objects :

var Node = {
  name: '',
  id: '',,
  parent: '',
  children: '',
  data: ''
}

var Community = {
  nodes: ''
}

var Data = {
  info: '',
  value: ''
}

Those are obviously simplified versions of the real deal, but I'd like to know how I can tell the javascript JSON deserializer to build the fields properly, using the objects I declared.

I need to make some sort of CMS for this so it's important that all the keys are available, even if they hold no value, which is why I want to declare objects and have the deserialiser use them.

For instance, I want to be able to access Community.nodes[3].data.info even if it wasn't set in the JSON file.

Saryk
  • 345
  • 1
  • 12

1 Answers1

0

A lot of people (including Microsoft ASP.NET) use the NuGet package Json.NET.

The JsonSerializer class offers a large degree of customisation over how objects are serialized.

However to access a deeply nested field like Community.people[3].job.salary you must make sure that there are no null nested objects before you access the last field.

In your example you would probably want to set Person.Job to be a default value or pass the Job in the constructor for Person.

If the issue is on the JavaScript side I suggest you take a look at the prototype pattern as a starting point and this question for reference to assigning to it from a JSON string.

ste-fu
  • 6,879
  • 3
  • 27
  • 46
  • To clarify, the C# part of this works perfectly, both serializing and deserializing. I'd like to create a web page that takes that JSON and allows me or a client to edit it, and notably add a 'Person' for example. So I'd like to be able to just instantiate a 'Person' object and manipulate it as an object before reserializing and saving the JSON file. – Saryk Jul 19 '17 at 09:46