1

There are a number of great ways to auto-generate C# code from JSON, such as here and here.

However, the resulting code doesn't include property initializers. For example, the following JSON:

{
"Name" : "Blastoise"
}

gets deserialized to this:

public class RootObject
{
    public string Name { get; set; }
}

Presumably this is by design, since the values used in the JSON will probably be overridden anyways, so adding initializers might just annoy people who don't want them.

But what if I want that? Short of manually adding every value by hand, is there a way to deserialize JSON to the following?

public class RootObject
{
    public string Name { get; set; } = "Blastoise";
}

Obviously in this case a manual edit is easy, but manual editing becomes tedious for larger JSON objects.

9
  • How would you expect such a tool to handle a case where I send you two objects, each with "Name" having a different value? The point of the POCO generators is that they merely create a generic, reusuable object structure. Commented Sep 23, 2015 at 20:34
  • Initialization is the deserialization of the json string. Commented Sep 23, 2015 at 20:37
  • For reference, Visual Studio does this on it's own now. You can paste JSON and XML as classes. Commented Sep 23, 2015 at 20:37
  • @DavidG, maybe you can elaborate more in an answer Commented Sep 23, 2015 at 20:46
  • @ArturoTorresSánchez I don't mean with initialisers, just creating the classes. Edit menu -> Paste special -> Paste JSON as classes Commented Sep 23, 2015 at 20:58

1 Answer 1

5

is there a way to deserialize JSON to the following?

Using the source code of the converter you mentioned.

A quick change at the line 204

sw.WriteLine(prefix + "public {0} {1} {{ get; set; }} = {2};", field.Type.GetTypeName(), field.MemberName, field.GetExamplesText());

gives me the result similar to what you described

internal class SampleResponse1
{

    [JsonProperty("Name")]
    public string Name { get; set; } = "Blastoise";
}
Sign up to request clarification or add additional context in comments.

Comments

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.