Convert JSON to C# inline class with values set

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.


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>