Matas Vaitkevicius
Matas Vaitkevicius

Reputation: 61401

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?

Upvotes: 9

Views: 2434

Answers (2)

hybrid
hybrid

Reputation: 1364

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.

Upvotes: 7

Matas Vaitkevicius
Matas Vaitkevicius

Reputation: 61401

So I have failed to find any out of the box solution - had to write my own.

Script below can be used as converter, it probably is full of bugs. Still it worked for everything I needed to do so far.

function Convert(jsonStr, classNr) {
  var i = classNr == undefined ? 0 : classNr;
  var str = "";
  var json = JSON.parse(jsonStr);
  for (var prop in json) {
    if (typeof(json[prop]) === "number") {
      if (json[prop] === +json[prop] && json[prop] !== (json[prop] | 0)) {
        str += prop + " = " + json[prop] + "M, ";
      } else {
        str += prop + " = " + json[prop] + ", ";
      }
    } else if (typeof(json[prop]) === "boolean") {
      str += prop + " = " + json[prop] + ", ";
    } else if (typeof(json[prop]) === "string") {
      str += prop + ' = "' + json[prop] + '", ';
    } else if (json[prop] == null || json[prop] == undefined) {
      str += prop + ' = null, ';
    } else if (typeof(json[prop]) === "object") {
      str += prop + " = " + Convert(JSON.stringify(json[prop]), i++) + ", ";
    }
  }
  return "new Class" + i + "{ " + str + " }";
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<textarea cols="100" rows="6">
  { "StingProperty" : "StringVal", "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, "Obj" : {"One" : 1, "Dec" : 1.1, "Str" : "Stringer", "Bolie" : true},"Obj1"
  : {"One" : 1, "Dec" : 1.1, "Str" : "Stringer", "Bolie" : true, "Obj2" : {"One" : 1, "Dec" : 1.1, "Str" : "Stringer", "Bolie" : true}} }
</textarea>
<input type="button" value="Just do it!" onclick="$('#result').append(Convert($('textarea').text()));" />
<div id="result"></div>

Upvotes: 2

Related Questions