Home > database >  How do I restructure this JSON object?
How do I restructure this JSON object?

Time:03-08

I want to convert json data from one format to another like below in c#. I want "Region" to be a list.

From:

{
        "Document": {
            "Regions": {
                "Region": {
                    "Color": "#FFFF0000",
                    "Type": "Rectangle",
                }
            }
        }
    }

To:

{
    "Document": {
        "Regions": {
            "Region": [{
                "Color": "#FFFF0000",
                "Type": "Rectangle"
            }]
        }
    }
}

CodePudding user response:

I think what you are really looking for as an end result is this:

The Region element seemed unneeded. All you need is a document with an array of regions.

I have provided C# code files for the old and new model with a function to convert from one to the other.

{
    "Document": {
        "Regions": [
            { "Color": "#FFFF0000", "Type": "Rectangle" }
        ]
    }
}

This is the model in C# would look like this:

// # original payload model
public class Rootobject
{
    public Document Document { get; set; }
}
public class Document
{
    public Regions Regions { get; set; }
}
public class Regions
{
    public Region Region { get; set; }
}
public class Region
{
    public string Color { get; set; }
    public string Type { get; set; }
}
// modified for region array
public class RootobjectMew
{
    public DocumentNew Document { get; set; }
}

public class DocumentNew
{
    public Region[] Regions { get; set; }
}

This would be a Converter Function to convert the old to the new model:

public RootobjectNew ConvertModel(Rootobject model)
{
    if (model == null) return null;
    return new RootobjectNew()
    {
        Document = new DocumentNew()
        {
            Regions = new[] { new Region { Color = model.Document.Regions.Region.Color, Type = model.Document.Regions.Region.Type } }
        }
    };
}
  • Related