1

Hi I am wondering if there is a way to convert a json object to explicit new object/List object for instance :

Convert this :

{
 "name":"John",
 "age":30,
 "cars":[ "Ford", "BMW", "Fiat" ]
}

into this c# code text:

new className() {
  Name = "John",
  Age = 30,
  Cars = new List (){"Ford", "BMW", "Fiat" }
 };

What I want to do is create the equivalent of a json code in to c# code.

  • Does this answer your question? [Convert Json String to C# Object List](https://stackoverflow.com/questions/22191167/convert-json-string-to-c-sharp-object-list) – Pavel Anikhouski Apr 23 '20 at 20:32

2 Answers2

3

You can use the JObject from Newtonsoft library

This is an example from the library

string json = @"{
  CPU: 'Intel',
  Drives: [
    'DVD read/writer',
    '500 gigabyte hard drive'
  ]
}";

JObject o = JObject.Parse(json);


Console.WriteLine(o.ToString());

Output

{
   "CPU": "Intel",
   "Drives": [
     "DVD read/writer",
     "500 gigabyte hard drive"
   ]
}

Or you can use jsonutils to create a C# equivalence class

And then use Newtonsoft to parse the Json object

MyObject obj = JsonConvert.DeserializeObject<MyObject>(jsonContent);
Rans
  • 569
  • 7
  • 14
0

You can use online services like https://www.jsonutils.com/

or

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++) + ", ";
    }
  }

  if (str.endsWith(', ')) {
    str = str.substring(0, str.length - 2);
  }

  return "new Class" + i + "{ " + str + " }";
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<textarea id="tin" cols="100" rows="6">
 {"A":12}
</textarea>
<input type="button" value="Just do it!" onclick="$('#result').text(Convert($('#tin').val()));" />
<div id="result"></div>

from https://stackoverflow.com/a/34590681/1932159

PurTahan
  • 789
  • 8
  • 24