0

My class structure is fixed but object variables(properties) are not fixed. Those data are configurable. I am creating a class with a dictionary but it is not working.

For ex.

{
"datamapItems": [
      {
        "paramName": "VE8321C",
        "datamapKey": {
          "module": 1,
          "id": 1391
        },
        "min": "0",
        "max": "40",
        "default": 222,
        "rateHz": 0,
        "timeoutMs": 0,
        "dataType": "uint16"
      }
   ]
}

For these JSON structure we have created following class structure. but it is not working. After serializing dictionary does not contain any value.

public class Datamap
{
    [JsonProperty("datamapItems")]
    public List<DatamapItem> datamapItems { get; set; }
}

public class DatamapItem
{
    public Dictionary<object, object> datamapitems = new Dictionary<object, object>();
    public DatamapKey datamapKey { get; set; }
}
public class DatamapKey
{
    public Dictionary<object, object> datamapitems = new Dictionary<object, object>();
}
er-sho
  • 9,581
  • 2
  • 13
  • 26
Suhel Patel
  • 278
  • 1
  • 12
  • Is this json you posted is right? means these is no curly braces outside `datamapItems` like `{ "datamapItems": [...]}` – er-sho Oct 11 '18 at 05:36
  • Thank you for pointing that. Yes there is a curly braces like { "datamapItems": [...] } – Suhel Patel Oct 11 '18 at 06:19

1 Answers1

0

If your objects are not fixed and data must be configurable then Newtonsoft.json has one feature that to be use here and that is [JsonExtensionData]. Read more

Extension data is now written when an object is serialized. Reading and writing extension data makes it possible to automatically round-trip all JSON without adding every property to the .NET type you’re deserializing to. Only declare the properties you’re interested in and let extension data do the rest.

Here i created a console app for your demonstration purpose.

class Program
{
    static void Main(string[] args)
    {
        //This is your input json string
        var inputJson = @"{
                      'datamapItems': [
                                   {
                                      'paramName': 'VE8321C',
                                      'datamapKey': {
                                                   'module': 1,
                                                   'id': 1391
                                      },
                                      'min': '0',
                                      'max': '40',
                                      'default': 222,
                                      'rateHz': 0,
                                      'timeoutMs': 0,
                                      'dataType': 'uint16'
                                    }
                                 ]
                           }";


        var result = JsonConvert.DeserializeObject<Datamap>(inputJson);  //Here you can deserialize your json


        DatamapKey datamapKey = new DatamapKey();
        datamapKey._DatamapKeys = new Dictionary<string, JToken>();
        datamapKey._DatamapKeys.Add("module", 1);
        datamapKey._DatamapKeys.Add("id", 1391);
        datamapKey._DatamapKeys.Add("ABC", 123);   //Here I added extra key/value pair to your inner object

        DatamapItem datamapItem = new DatamapItem();
        datamapItem._DatamapItems = new Dictionary<string, JToken>();
        datamapItem._DatamapItems.Add("paramName", "VE8321C");
        datamapItem._DatamapItems.Add("datamapKey", JToken.FromObject(datamapKey));
        datamapItem._DatamapItems.Add("min", "0");
        datamapItem._DatamapItems.Add("max", "40");
        datamapItem._DatamapItems.Add("default", 222);
        datamapItem._DatamapItems.Add("rateHz", 0);
        datamapItem._DatamapItems.Add("timeoutMs", 0);
        datamapItem._DatamapItems.Add("dataType", "uint16");

        datamapItem._DatamapItems.Add("PQR", "123");   //Here I added extra key/value pair to your outer object
        datamapItem._DatamapItems.Add("XYZ", "123");    //Here I added extra key/value pair to your outer object

        Datamap datamap = new Datamap();
        datamap.datamapItems = new List<DatamapItem>();
        datamap.datamapItems.Add(datamapItem);

        string json = JsonConvert.SerializeObject(datamap);   //Here you can serialize your custom key/value pair 

        JObject parsed = JObject.Parse(json);
        Console.WriteLine(parsed);

        Console.ReadLine();
    }
}

public class DatamapKey
{
    [JsonExtensionData]
    public IDictionary<string, JToken> _DatamapKeys;
}

public class DatamapItem
{
    [JsonExtensionData]
    public IDictionary<string, JToken> _DatamapItems;
}

public class Datamap
{
    public List<DatamapItem> datamapItems { get; set; }
}

Output:

enter image description here

Edit:

1) For below json

{ "agentRegistry": { "agents": [ { "type": "drv", "id": "drv3", "port": 3, "config": { "mode": "currentSetPoint", "config": { } } }, { "type": "mmc", "id": "mmc2", "port": 2, "config": { "mode": "analogIn", "config": { "max": 21000, "min": 300, "conversion": [ ] } }}]}}

Classes:

public class Config2
{
    [JsonExtensionData]
    public IDictionary<string, JToken> _config2;
}

public class Config
{
    [JsonExtensionData]
    public IDictionary<string, JToken> _config;
}

public class Agent
{
    [JsonExtensionData]
    public IDictionary<string, JToken> _agents;
}

public class AgentRegistry
{
    public List<Agent> agents { get; set; }
}

public class RootObj
{
    public AgentRegistry agentRegistry { get; set; }
}
er-sho
  • 9,581
  • 2
  • 13
  • 26
  • Can you please help me with below JSON? { "agentRegistry": { "agents": [ { "type": "drv", "id": "drv3", "port": 3, "config": { "mode": "currentSetPoint", "config": { } } }, { "type": "mmc", "id": "mmc2", "port": 2, "config": { "mode": "analogIn", "config": { "max": 21000, "min": 300, "conversion": [ ] } }}]}} – Suhel Patel Oct 11 '18 at 09:15
  • {"chains": [{"name": "srvoOiInpt1","type": "rawInptChn","updateIntervalMs": 100,"config": {"inptAgntId": "mmc2","datamapWriter": {"datamapKey": {"module": 0,"id": 110}}}},{"name": "servoOilPresRedncy","type": "redncyChn","updateIntervalMs": 100,"config": {"primaryItemInput": {"datamapKey": {"module": 1,"id": 110}},"secondaryItemInput": {"datamapKey": {"module": 2,"id": 111}},"datamapWriter": {"datamapKey": {"module": 0,"id": 999}}}},{"name": "srvOilOpt1","type": "rawOptChn","updateIntervalMs": 10,"config": {"outputAgentId": "drv3","datamapInput": {"datamapKey": {"module": 1,"id": 106}}}}]} – Suhel Patel Oct 11 '18 at 09:23
  • which json i have to consider? 1st or 2nd – er-sho Oct 11 '18 at 09:28
  • both...:) help me on both one... please – Suhel Patel Oct 11 '18 at 09:31
  • @SuhelPatel, view **Edit** section in answer, I added class structure for 1st json but i don't have enough time to generate for 2nd, but you may refer same class structure to build for 2nd one – er-sho Oct 11 '18 at 10:19
  • Can you help me out to put above json data into database (SQL Server) and Retrieve from database too.. plz – Suhel Patel Oct 17 '18 at 04:18
  • Could you please ask new question regarding your query bcoz here if i added then there is 2 different solution for same question and it breaks integrity of question that u asked and answer that provided and in future any other user are confused if they follow your question. After post your question you can send me a link in comment below or any expert can help you :) – er-sho Oct 17 '18 at 05:35
  • here is the link : https://stackoverflow.com/questions/52831181/read-data-from-json-into-class-and-store-into-database-sqlserver/52831497 – Suhel Patel Oct 17 '18 at 06:16
  • My json: { "data": { "mapItems": [ { "mapKey": { "module": 500 }, "Name": "Test", "Desc": "#1", "min": 0 } } json i want: { "data": { "mapItems": [ { "Name": "Test", "Desc": "#1", "mapKey": { "module": 500 }, "min": 0 } } how to generate above json? – Suhel Patel May 13 '19 at 08:15
  • can we generate above json according to condition? for example : - According to condition 1 json should be {'datamapItems': [{'paramName': 'VE8321C','datamapKey': {'module': 1,'id': 1391},'min': '0','max': '40',}]} and according to condition 2 json should be {'datamapItems': [{'paramName': 'VE8321C','min': '0','max': '40',}]}. This both should be on same json. – Suhel Patel Jun 21 '19 at 05:04