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.

1

2 Answers 2

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);
Sign up to request clarification or add additional context in comments.

Comments

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

2 Comments

Thanks for your answer that is a great tool but I dont want just create the class with its attributes, What I want is create the initialization of those clases with the content of the json.
see the answer, i add new solution @DanielMoralesArias

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.