0

I want to create a JSON value in matrix form as shown below. I want a new line after every 10 records.

{
"defaults": [
          -850,-850,-850,-850,-850,-850,-850,-850,-850,-850,
          -850,-850,-500,-780,-780,-780,-780,-780,-780,-780,
          -70,-70,-60,-50
        ]
}

The model class which I have created for JSON is given below. As the values can be of any data type, for example, boolean or double or string, I have used List<object> as the data type.

public class Parameter
{
    public List<object> defaults { get; set; }
}

I have stored the values in the database as a single record. So at the time of fetching the data, I need to split it and have to store in an array.

string[] splitDefault = { (value shown in JSON) };

I have written the below given code to assign a value to the object:

Parameter para = new Parameter();
para.defaults = new List<object>();

foreach (string item in splitDefault)
{
 if (paraDataType == "bool")
 {
    bool defaultValue = false;
    bool.TryParse(item, out defaultValue);
    para.defaults.Add(defaultValue);
 }
 else if (paraDataType == 9)
 {
    double defaultValue = 0;
    double.TryParse(item, out defaultValue);
    para.defaults.Add(defaultValue);
 }
}

The JSON value I am getting is like this:

{
    "defaults": [ 0, 350, 550, 800, 850, 1000, 1050, 1150, 1200, 1300, 1400, 1500, 1600, 1700, 1800, 1900 ]
}
Suhel Patel
  • 278
  • 1
  • 12

1 Answers1

1

It's a little hacky, but you could create a custom JsonConverter which will write out the list values while toggling the Formatting parameter of the JsonWriter at the desired intervals:

public class CustomFormattingArrayConverter : JsonConverter
{
    private int ItemsPerLine { get; set; }

    public CustomFormattingArrayConverter(int itemsPerLine)
    {
        if (itemsPerLine < 1) throw new ArgumentException("itemsPerLine must be 1 or more");
        ItemsPerLine = itemsPerLine;
    }

    public override bool CanConvert(Type objectType)
    {
        return objectType == typeof(List<object>);
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        List<object> list = (List<object>)value;
        writer.WriteStartArray();
        for (int i = 0; i < list.Count; i++)
        {
            if (i % ItemsPerLine == 0) writer.Formatting = Formatting.Indented;
            serializer.Serialize(writer, list[i]);
            if (i % ItemsPerLine == 0) writer.Formatting = Formatting.None;
        }
        writer.Formatting = Formatting.Indented;
        writer.WriteEndArray();
    }

    public override bool CanRead
    {
        get { return false; }
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }
}

Then use it like this:

var settings = new JsonSerializerSettings
{
    Converters = new List<JsonConverter> { new CustomFormattingArrayConverter(10) },
    Formatting = Formatting.Indented
};

var json = JsonConvert.SerializeObject(parameter, settings);

Working demo: https://dotnetfiddle.net/aBwAED

Brian Rogers
  • 125,747
  • 31
  • 299
  • 300
  • Can i achive given json through customfomatting? My json: { "data": { "mapItems": [ { "mapKey": { "module": 500 }, "Name": "Test", "Desc": "#1", "min": 0 } }. The Json i want: { "data": { "mapItems": [ { "Name": "Test", "Desc": "#1", "mapKey": { "module": 500 }, "min": 0 } } how to generate above json? – Suhel Patel May 14 '19 at 01:28
  • @SuhelPatel You should create a [new question](https://stackoverflow.com/questions/ask) describing what you are trying to do, what you have tried and where you are getting stuck. Comments are not a good place to ask new questions. – Brian Rogers May 14 '19 at 14:57
  • Can you please solve this : https://stackoverflow.com/questions/56697644/serialize-json-object-as-per-the-condition-using-c-sharp-and-json-net – Suhel Patel Jun 21 '19 at 06:37