Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert JSON to C# inline class with values set

I need to generate test cases (using IEnumerable<TestCaseData>) from JSON objects that have values set. I couldn't find any tools online that would generate C# classes that have values set (Plenty that generate classes). Deserializing Json in test cases would invalidate test (One should only be testing the code), so I did this regex.

It's not perfect but worked just fine with most basic well formatted JSON when all properties are of same type (decimals or bools), pattern: "([a-zA-Z]?[a-zA-Z0-9].*)" ?: ?((true|false|null)|([\d].*)) , replace $1 = $2M however when there are many types and they are mixed I get screwed.

I am sure someone ran into this before me and I am reinventing wheel so in a nutshell.

How do I make this:

{
    "LegalFeeNet": 363.54,
    "LegalFeeVat": 72.708,
    "DiscountNet": 0.0,
    "DiscountVat": 0.0,
    "OtherNet": 12.0,
    "OtherVat": 2.4,
    "DisbursementNet": 220.0,
    "DisbursementVat": 0.0,
    "AmlCheck": null,
    "LegalSubTotal": 363.54,
    "TotalFee": 450.648,
    "Discounts": 0.0,
    "Vat": 75.108,
    "DiscountedPrice": 360.5184,
    "RecommendedRetailPrice": 450.648,
    "SubTotal": 375.54,
    "Name": "Will",
    "IsDiscounted": false,
    "CustomerCount": 3
}

to become this:

ClassName {
    LegalFeeNet = 363.54M,
    LegalFeeVat = 72.708M,
    DiscountNet = 0.0M,
    DiscountVat = 0.0M,
    OtherNet = 12.0M,
    OtherVat = 2.4M,
    DisbursementNet = 220.0M,
    DisbursementVat = 0.0M,
    AmlCheck = nullM,
    LegalSubTotal = 363.54M,
    TotalFee = 450.648M,
    Discounts = 0.0M,
    Vat = 75.108M,
    DiscountedPrice = 360.5184M,
    RecommendedRetailPrice = 450.648M,
    SubTotal = 375.54M,
    Name = "Will",
    IsDiscounted = false,
    CustomerCount = 3
}

What fastest/most convenient solution is to generate C# classes that have properties set from JSON objects?

like image 825
Matas Vaitkevicius Avatar asked Dec 07 '15 11:12

Matas Vaitkevicius


1 Answers

I was also here in search of a solution to the same problem.

The accepted answer missed some features I wanted, so ended up creating this https://jsontocsharpconverter.web.app/

Hopefully.. it helps someone.

like image 91
hybrid Avatar answered Oct 22 '22 00:10

hybrid