1

I have a List of DataObject classes:

public class DataObject
    {
        public string Name { get; set; }

        public List<Field> Fields { get; set; }
    }
}



public class Field
{

    public string Name { get; set;}
    public string Type { get; set; }
    public Object Value { get; set; }

    public Field(string name, string type, string value)
    {
        Name = name;
        Type = type;
        if(type == "string") Value = (string)value;
        else Value = Int32.Parse(value);
    }
}

and i would like to serialize List made of DataObject classes to .json file. the way I show below using Json.NET, I have tried few scenarios but didn't find out how to do this.

Example:

Field field1 = new Field("Brand", "string", "Volvo);
Field field2 = new Field("Power", "int", 200);
List<Field> fields = new List<Field>{field1, field2};
DataObject car = new DataObject{
   Name = "Car",
   Fields = list
}
List<DataObjects> objects = new List<DataObjects>{car};

Result:

{
 "Car":{
   "Brand" : "Volvo",
   "Power" : 200
  }
}
1
  • What is the JSON supposed to look like if there are multiple DataObjects in the list? Commented May 9, 2019 at 5:51

1 Answer 1

3

Using Newtonsoft.Json, Serialization is rather easy. I took your code and added the following line:

string json = JsonConvert.SerializeObject(objects, Newtonsoft.Json.Formatting.Indented);

and it gave me the following output:

[
  {
    "Name": "Car",
    "Fields": [
      {
        "Name": "Brand",
        "Type": "string",
        "Value": "Volvo"
      },
      {
        "Name": "Power",
        "Type": "int",
        "Value": 200
      }
    ]
  }
]
Sign up to request clarification or add additional context in comments.

1 Comment

I get it, but how to make variable Name (in my case for example "Brand"), a tag for variable Value (for example "Volvo") to get "Brand" : "Volvo" etc.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.