Home > Software design >  Serialize a JSON object without property name having a list of custom object in C#
Serialize a JSON object without property name having a list of custom object in C#

Time:08-05

I have model as below:

public class CustomModel
    {        
        public string Data1 { get; set; }
        public string Data2 { get; set; }
    }

public class root
    {   
        public List<CustomModel> data { get; set; }
    }

My payload is as below:

List<CustomModel> cms = new List<CustomModel>();

                CustomModel cm1 = new CustomModel();
                cm1.Data1 = "a";
                cm1.Data2 = "b";
                cms.Add(cm1);

                CustomModel cm2 = new CustomModel();
                cm2.Data1 = "D";
                cm2.Data2 = "E";
                cms.Add(cm2);

                BaseClass baseClass = new BaseClass();
                baseClass.data = cms;

My JSON is:

var json = new JavaScriptSerializer().Serialize(baseClass);

And Result is:

{"data":[{"data1":"a","data2":"b"},{"data1":"D","data2":"E"}]}

BUT I need: without the "data" property as below:

{[{"data1":"a","data2":"b"},{"data1":"D","data2":"E"}]}

I tried the below function:

public static IEnumerable<object> GetPropertyValues<T>(T input)
            {
                return input.GetType()
                    .GetProperties()
                    .Select(p => p.GetValue(input));
            }
            

Like

var value_only = GetPropertyValues(baseClass);
var json = new JavaScriptSerializer().Serialize(value_only);
BUT it returns [[{"data1":"a","data2":"b"},{"data1":"D","data2":"E"}]]

Is there anywasy to do it other than manually adding? Please help.

CodePudding user response:

Note that {[{"data1":"a","data2":"b"},{"data1":"D","data2":"E"}]} is not valid json. In Json objects, data/values are organized by (named) properties.

However, here you seem to want a (root) Json object containing a value being Json array, but that value is not associated with a Json object property, thus not being valid Json.

If you really want invalid Json, i suggest you serialize the List<CustomModel> instance instead of the root model instance, resulting in a Json array, and then manually adding the surrounding { and } to the serialized Json string, thus giving you your desired invalid Json result:

var json = new JavaScriptSerializer().Serialize(baseClass.data);
var desiredResult = "{"   json   "}";

CodePudding user response:

you don't need root class (or base class you must to deside what is name. Just use

var json = new JavaScriptSerializer().Serialize(cms);

PS.

And it is time to select a modern serializer.

  • Related