Kishan Sojitra Kishan Sojitra - 6 months ago 12
JSON Question

How to create Json with Sub Fields using C#?

I'm very new to Json, I want to create this type of Json string.

{
"myID": "3",
"field1": "Instructions",
"field2": "Instructions",
"field3": "30acdd0d-4b72-498a-8f47-2d372581e5e8",
"field4": {
"subField1":{
"value1":"xyz",
"value2":"abc",
"value3":"pqr"
}
}
}

Answer

you can try like

public class Example
{
        public string myID { get; set; }
        public string field1 { get; set; }
        public string field2 { get; set; }
        public string field3 { get; set; }
        public Field4 field4 { get; set; }
}
public class Field4
{
        public SubField1 subField1 { get; set; }
}

public class SubField1
{
        public string value1 { get; set; }
        public string value2 { get; set; }
        public string value3 { get; set; }
}

and then

Example objExample = new Example();
objExample.myID = "3";
objExample.field1 = "Instructions";
objExample.field2 = "Instructions";
objExample.field3 = "30acdd0d-4b72-498a-8f47-2d372581e5e8";

Field4 objF4 = new Field4();
SubField1 objSubField1 = new SubField1();

objSubField1.value1 = "xyz";
objSubField1.value2 = "xyz";
objSubField1.value3 = "xyz";

objF4.subField1 = objSubField1;
objExample.field4 = objF4;

var jsonResult= JsonConvert.SerializeObject(objExample);