json2csharp / json2csharpcodegenerator Goto Github PK
View Code? Open in Web Editor NEWLicense: Microsoft Reciprocal License
License: Microsoft Reciprocal License
Add MIT or whichever liscence.
Change the main library project to target .NET Standard 2.0 : Newtonsoft and Pluralization librairy
Check why the pluralization dll was not found when calling it from other code
{
"Id": 123456123456789, // long datatype is translated as object. it should long not object
"Data": [
{
"Name": "Car",
"Year": 2000
},
{
"Name": "Motorbike",
"Year": 2010
}
]
}
The json above should have constructor to set default value of list to be empty list, not null.
public class Datum
{
[JsonProperty("Name")]
public string Name { get; set; }
[JsonProperty("Year")]
public int Year { get; set; }
}
public class Root
{
public Root()
{
List<Datum> = new List<Datum>();
}
[JsonProperty("Id")]
public long Id { get; set; }
[JsonProperty("Data")]
public List<Datum> Data { get; set; }
}
If the same object is repeated elsewhere a new class is created -> bug
TEST CASE # 7,
Example:
{
"testobject":[
{
"testprop":"test",
"testprop2":"test2"
},
{
"testprop":"test",
"testprop2":"test2"
}
],
"testparent":{
"testobject":[
{
"testprop":"test",
"testprop2":"test2"
},
{
"testprop":"test",
"testprop2":"test2"
}
]
}
}
Should return
public class Root
{
public List<Testobject> Testobject { get; set; }
public Testparent Testparent { get; set; }
}
public class Testobject
{
public string Testprop { get; set; }
public string Testprop2 { get; set; }
}
public class Testparent
{
public List<Testobject> Testobject { get; set; }
}
Hi,
one thing that may (or may not) be useful is conversion of the following type:
{
"name": "Peter" // Person's name
}
(Yes, I know JSON comments are non-standard.)
This JSON would be translated into:
public class Root
{
/// <summary>Person's name</summary>
public string name { get; set; }
}
I guess it's not that common thing to do but I'll leave it here for consideration.
Thanks!
Exception: Unable to cast object of type 'Newtonsoft.Json.Linq.JArray' to type 'Newtonsoft.Json.Linq.JObject'.
When converting from Json to C# I realized that when same property of class use type Datetime the using statement is not implemented.
I found this on class CSharpCodeWriter.WriteFileStart
sw.AppendLine("using System;");
I my tests from the website It's not working.
Hi,
if the JSON uses an escaped " within an String the conversion fails.
And the server returns "Wrong JSON format"
This is a simple example that breaks the converter:
{ "someText": " some \"special\" Text" }
Huita
public Opening_hours opening_hours { get; set; }
should be
public Opening_Hours opening_hours { get; set; } ?
if a json field name contains a hyphen, code like this is generated:
public List<EStatu> e-status { get; set; }
no valid code.
what would work:
[JsonProperty("e-status")] public List<EStatu> e_status { get; set; }
Wrong thing
The 'Use JsonPropertyName (.NET Core)' and 'Generate Immutable Classes' settings used together result in the JsonPropertyName
attribute being applied to ctor parameters. This is invalid and results in compiler error CS0592.
I have a complex json format with the same name property. In this case is the Data property. The first Data class is not generated and resulted the wrong class
notwork.txt
. Here's the attachment.
You need to escape keyword names such as return.
Example JSON:
{ "response": { "value": { "search_params": { "to_type": "airport", "flyFrom_type": "airport" }, "time": 1, "connections": [], "currency": "pln", "currency_rate": 0.2348, "data": { "airlines": [ "W6", "FR" ], "baglimit": { "hand_height": 40, "hand_length": 55, "hand_weight": 7, "hand_width": 23, "hold_height": 52, "hold_length": 78, "hold_weight": 20, "hold_width": 28, "hold_dimensions_sum": 158 }, "bags_price": {}, "booking_token": "oKWrjE3p79Fphzv+baF3C2h1PDgCet9WaEXSzPuPgCEbnZfp1jYeu4WPBYkWhnvFVdMUHtSDW6qgykuuve1Fglx/Cp7ojKGgP1wN57eDDm7174lwXFwCaExwY1oviADeYzWzkvgFnSYx5w19mnX0t3KunnedJScRvA426om/JqXmCfbfEnVyryB+6ywjr8CmwBhAaTGz8UFxe2F+S2Ck6XhTPyoaf8VI4gBOnoVY1rlXVE/Xi+9bnpqQN+jP8i74zmLVb4LiWhMreQqaG1acc0xIEdZQxq1qllX0t9JSsYyZ8kS41KheurCLH/u2mpJgowJnySLQ/w5a0J7yKb7dBF+/6CVD52a+FH6PibsRXJWNQso336gGlqfjIQ72f8Oi2Ep7IXzuKPOvC2W/Ucp5Le+n0kz6VckLLrol1IkFwCAkP0Pyf5v6FrsWEYF53la5Ig3dLDPy32Yhpu9L1TqImtfryq3mFr53Fh6Z/hZoaJH7yfd2h8aqj92snLfCkvl72VAfJITkdE8vMNGz5quCYw60mgUdXvBMzaNeSPgtWMKRM+kzzTb2YJwmBhjS8B8Qa8j/zixcnMEiO4VdksgZq2dcFpm7fjx670ml0y87G4+ebECvzDaP8oClNJ2WmFtl3R8/EQ+2+LaUKrktN/OWDJT92sfS1K7LP1OTC/1uQrHG4vSqo0A+SofRTw2UP/08kxoJoc6IkrsdmVPQlPRIPi/r9cPsWaRe1JsoBYCa0tz2FWWXr1pLX3RQjrNUq2Vo8Ns6/FItzkr4CNhtHOTin6qITvyTqio610v5ovrhS4lL13yIYfHu0s3n0d/Gp/DWryGOZsIC5v+D9S8P/s5hCP9m51gizRSNjpQn/LpFin23pztXPRR6gvHVXZKRhUOAdyyis5gPHL+9A7n7THciyKVs0bM3XhQG3EpUWhCYUpjVRPF69+2RXENVCOF3Ys9SfBjsv3vcsJTMNQs2Fh+Sk1hHnY9WkgWs3EK8lN0mx2NOcdKU6nAxg4np4QtyF/I5SU33wMBxXdJ3BpltM33TGUG9xpeN0DPLP0S1oXfjIdGfBrLPJqpq7S2QC44BekgXdYYje92wUW7aJYAJhaJi2e93Q5JGf3V6caaxWTa8xsQ=", "cityFrom": "Prague", "cityTo": "Frankfurt", "conversion": { "EUR": 104 }, "countryFrom": { "code": "CZ", "name": "Czechia" }, "countryTo": { "code": "DE", "name": "Germany" }, "deep_link": "https://www.kiwi.com/deep?from=PRG&to=FRA&departure=04-12-2018&return=06-12-2018&flightsId=4210030485405823_0%7C3971436194349625_0%7C3971436206433809_0%7C3908763979435451_0%7C3956043040686669_0&price=104&passengers=1&affilid=kayak_en&lang=en¤cy=EUR&booking_token=oKWrjE3p79Fphzv+baF3C2h1PDgCet9WaEXSzPuPgCEbnZfp1jYeu4WPBYkWhnvFVdMUHtSDW6qgykuuve1Fglx/Cp7ojKGgP1wN57eDDm7174lwXFwCaExwY1oviADeYzWzkvgFnSYx5w19mnX0t3KunnedJScRvA426om/JqXmCfbfEnVyryB+6ywjr8CmwBhAaTGz8UFxe2F+S2Ck6XhTPyoaf8VI4gBOnoVY1rlXVE/Xi+9bnpqQN+jP8i74zmLVb4LiWhMreQqaG1acc0xIEdZQxq1qllX0t9JSsYyZ8kS41KheurCLH/u2mpJgowJnySLQ/w5a0J7yKb7dBF+/6CVD52a+FH6PibsRXJWNQso336gGlqfjIQ72f8Oi2Ep7IXzuKPOvC2W/Ucp5Le+n0kz6VckLLrol1IkFwCAkP0Pyf5v6FrsWEYF53la5Ig3dLDPy32Yhpu9L1TqImtfryq3mFr53Fh6Z/hZoaJH7yfd2h8aqj92snLfCkvl72VAfJITkdE8vMNGz5quCYw60mgUdXvBMzaNeSPgtWMKRM+kzzTb2YJwmBhjS8B8Qa8j/zixcnMEiO4VdksgZq2dcFpm7fjx670ml0y87G4+ebECvzDaP8oClNJ2WmFtl3R8/EQ+2+LaUKrktN/OWDJT92sfS1K7LP1OTC/1uQrHG4vSqo0A+SofRTw2UP/08kxoJoc6IkrsdmVPQlPRIPi/r9cPsWaRe1JsoBYCa0tz2FWWXr1pLX3RQjrNUq2Vo8Ns6/FItzkr4CNhtHOTin6qITvyTqio610v5ovrhS4lL13yIYfHu0s3n0d/Gp/DWryGOZsIC5v+D9S8P/s5hCP9m51gizRSNjpQn/LpFin23pztXPRR6gvHVXZKRhUOAdyyis5gPHL+9A7n7THciyKVs0bM3XhQG3EpUWhCYUpjVRPF69+2RXENVCOF3Ys9SfBjsv3vcsJTMNQs2Fh+Sk1hHnY9WkgWs3EK8lN0mx2NOcdKU6nAxg4np4QtyF/I5SU33wMBxXdJ3BpltM33TGUG9xpeN0DPLP0S1oXfjIdGfBrLPJqpq7S2QC44BekgXdYYje92wUW7aJYAJhaJi2e93Q5JGf3V6caaxWTa8xsQ=", "distance": 406.5, "duration": { "departure": 15600, "return": 34800, "total": 50400 }, "facilitated_booking_available": false, "flyFrom": "PRG", "flyTo": "FRA", "has_airport_change": false, "id": "4210030485405823_0|3971436194349625_0|3971436206433809_0|3908763979435451_0|3956043040686669_0", "local_arrival": "2018-12-04T16:35:00.000Z", "local_departure": "2018-12-04T12:15:00.000Z", "nightsInDest": 2, "pnr_count": 5, "price": 104, "quality": 239.99966, "rank": 0.0092, "route": [ { "airline": "FR", "bags_recheck_required": false, "cityFrom": "Prague", "cityTo": "Budapest", "combination_id": "4210030485405823", "equipment": null, "fare_basis": "NZ1299DC", "fare_classes": "N", "fare_family": "", "flight_no": 4092, "flyFrom": "PRG", "flyTo": "BUD", "guarantee": false, "id": "4210030485405823_0", "last_seen": "2018-11-08T15:30:07.000Z", "local_arrival": "2018-12-04T13:25:00.000Z", "local_departure": "2018-12-04T12:15:00.000Z", "operating_carrier": null, "refresh_timestamp": "2018-11-08T15:30:07.000Z", "return": 0, "utc_arrival": "2018-12-04T12:25:00.000Z", "utc_departure": "2018-12-04T11:15:00.000Z", "vehicle_type": "aircraft" }, { "airline": "W6", "bags_recheck_required": false, "cityFrom": "Budapest", "cityTo": "Frankfurt", "combination_id": "3971436194349625", "equipment": null, "fare_basis": "PRREG", "fare_classes": "P", "fare_family": "", "flight_no": 2311, "flyFrom": "BUD", "flyTo": "FRA", "guarantee": true, "id": "3971436194349625_0", "last_seen": "2018-11-08T15:52:47.000Z", "local_arrival": "2018-12-04T16:35:00.000Z", "local_departure": "2018-12-04T14:50:00.000Z", "operating_carrier": null, "refresh_timestamp": "2018-11-08T15:52:47.000Z", "return": 0, "utc_arrival": "2018-12-04T15:35:00.000Z", "utc_departure": "2018-12-04T13:50:00.000Z", "vehicle_type": "aircraft" }, { "airline": "FR", "bags_recheck_required": false, "cityFrom": "Frankfurt", "cityTo": "Venice", "combination_id": "3971436206433809", "equipment": null, "fare_basis": "NZ999DC", "fare_classes": "N", "fare_family": "", "flight_no": 2416, "flyFrom": "FRA", "flyTo": "TSF", "guarantee": false, "id": "3971436206433809_0", "last_seen": "2018-11-08T15:43:23.000Z", "local_arrival": "2018-12-06T14:30:00.000Z", "local_departure": "2018-12-06T13:10:00.000Z", "operating_carrier": null, "refresh_timestamp": "2018-11-08T15:43:23.000Z", "return": 1, "utc_arrival": "2018-12-06T13:30:00.000Z", "utc_departure": "2018-12-06T12:10:00.000Z", "vehicle_type": "aircraft" }, { "airline": "FR", "bags_recheck_required": false, "cityFrom": "Venice", "cityTo": "City of Brussels", "combination_id": "3908763979435451", "equipment": null, "fare_basis": "NZ999DC", "fare_classes": "N", "fare_family": "", "flight_no": 6056, "flyFrom": "TSF", "flyTo": "CRL", "guarantee": true, "id": "3908763979435451_0", "last_seen": "2018-11-08T15:06:39.000Z", "local_arrival": "2018-12-06T18:45:00.000Z", "local_departure": "2018-12-06T17:05:00.000Z", "operating_carrier": null, "refresh_timestamp": "2018-11-08T15:06:39.000Z", "return": 1, "utc_arrival": "2018-12-06T17:45:00.000Z", "utc_departure": "2018-12-06T16:05:00.000Z", "vehicle_type": "aircraft" }, { "airline": "FR", "bags_recheck_required": false, "cityFrom": "City of Brussels", "cityTo": "Prague", "combination_id": "3956043040686669", "equipment": null, "fare_basis": "NZ1299DC", "fare_classes": "N", "fare_family": "", "flight_no": 2121, "flyFrom": "CRL", "flyTo": "PRG", "guarantee": true, "id": "3956043040686669_0", "last_seen": "2018-11-08T15:54:24.000Z", "local_arrival": "2018-12-06T22:50:00.000Z", "local_departure": "2018-12-06T21:20:00.000Z", "operating_carrier": null, "refresh_timestamp": "2018-11-08T15:54:24.000Z", "return": 1, "utc_arrival": "2018-12-06T21:50:00.000Z", "utc_departure": "2018-12-06T20:20:00.000Z", "vehicle_type": "aircraft" } ], "routes": [ "- PRG\n- FRA", "- FRA\n- PRG" ], "transfers": [], "type_flights": [ "lcc-FR", "lcc-W6" ], "utc_arrival": "2018-12-04T15:35:00.000Z", "utc_departure": "2018-12-04T11:15:00.000Z" } } } }
The return comes up as return and then it messes up the file. It should be @return
.
List of reserved words (for your convenience):
abstract as base bool break byte case catch char checked class const continue decimal default delegate do double else enum event explicit extern false finally fixed float for foreach goto if implicit in int interface internal is lock long namespace new null object operator out override params private protected public readonly ref return sbyte sealed short sizeof stackalloc static string struct switch this throw true try typeof uint ulong unchecked unsafe ushort using virtual void volatile while
They should be replaced each reserved word with @reservedword.
JsonPropertyNane is not working properly in c# .net core
I tried
[JsonPropertyName("security_skill")]
public SecuritySkill SecuritySkill;
and had to manually change it to
[JsonPropertyName("security_skill")]
public Security_Skill Security_Skill;
Example
{
"test" : "test "tae " tet"
}
This is throwing error should remove " before analyzing json
For instance, this:
{
"class": "user"
}
ends up with:
public class Root{
public String class;
}
But in java, class
is a reserved word, so it should go for:
public class Root{
@JsonProperty("class")
public String rootClass; // Or whatever other name (className, for example)
}
Hello, I can see you just bought json2csharp.com as it's domain already got expired.. Anyway it's good to see another one, but the bad that that it doesn't be like the old one, but it's too bad to see it send to the server and return the class string, it should be even easier than that, you should make it be done within Javascript to remove any delays that might take (2-5s) sometimes depends on how long the data is.
Also you should consider putting '@' sign before any keyword like for example having a json with class name = event or continue (we all know that event and continue are C# Keywords, so they need to be transfered to @event and @continue), you can also add some small other stuff like putting the [JsonProperty("Name")] instead of the name itself (make it a radio button option) and should be with 2 modes: camel case and pascal case .. All of these could be awesome and powerful suggestions.
It would be cool this available as vs extension were we can:
Rigth click the .json file and convert to c# models specifying the output folder.
Also this could be a global nuget package were we can run from terminal like:
dotnet Json2CSharpCodeGenerator -f myfile.json -o myfile.cs
Hi
Your converter lags support for nested arrays.
Here is an example JSON
{
"one_time":false,
"buttons":[
[
{
"action":{
"type":"location",
"payload":"{"button": "1"}"
}
}
],
[
{
"action":{
"type":"open_app",
"app_id":6979558,
"owner_id":-181108510,
"hash":"sendKeyboard",
"label":"Отправить клавиатуру"
}
}
],
[
{
"action":{
"type":"vkpay",
"hash":"action=transfer-to-group&group_id=181108510&aid=10"
}
}
],
[
{
"action":{
"type":"text",
"payload":"{"button": "1"}",
"label":"Negative"
},
"color":"negative"
},
{
"action":{
"type":"text",
"payload":"{"button": "2"}",
"label":"Positive"
},
"color":"positive"
},
{
"action":{
"type":"text",
"payload":"{"button": "2"}",
"label":"Primary"
},
"color":"primary"
},
{
"action":{
"type":"text",
"payload":"{"button": "2"}",
"label":"Secondary"
},
"color":"secondary"
}
]
]
}
Hey 👋
if on the JSON is a Variable Name is like 'protected', 'private', 'public', 'static',... then it takes on C# a error.
I would implement, if it's like these Names, it use JsonProperty and make Pascal Case.
yea
Issue: Missing "query" in the class definition.
Input:
{"_source":{"includes":["hubmsgid"]}},"size":10,"query":"test"}
Output:
public class Source {
public List includes { get; set; }
}
public class Root {
public Source _source { get; set; }
}
Sample json:
{
"1_star": 7,
"2_star": 6,
"3_star": 10,
"4_star": 19,
"5_star": 151
}
C# Converted:
public class Root {
public int 1_star { get; set; }
public int 2_star { get; set; }
public int 3_star { get; set; }
public int 4_star { get; set; }
public int 5_star { get; set; }
}
C# does not allow name of anything have digit at start.
Expected results:
public class Root {
//varinat 1
[JsonProperty("1_star ")]
public int One_star { get; set; }
//varinat 2
[JsonProperty("2_star ")]
public int d2_star { get; set; }
}
[
{
"ID":"{7D7891AF-69E0-4542-BE8A-0B1FE073B211}",
"Description":""
},
{
"ID":"{7D7891AF-69E0-4542-BE8A-0B1FE073B211}",
"Description":""
}
]
expected
// Root myDeserializedClass = JsonConvert.DeserializeObject<List>(myJsonResponse);
public class OBJECTT
{
[JsonProperty("ID")]
public string ID { get; set; }
[JsonProperty("Description")]
public string Description { get; set; }
}
When I paste the JSON to convert it to C#, if I click Use Pascal Case, it is always adding JsonProperty attribute on properties. I am using .NET Core's JsonSerializer. I don't want to add a new dependency to my project. Even when I unclick Add JsonProperty Attributes, it always adds them.
Please consider provide a option for convert number to decimal
, not double
, Thank you.
If you have a json to convert in java pojo with a field called "return", this creates a problem on the Java pojo obviously.
This is an exmaple:
{ "passengers": { "adults": 1 }, "route": { "outward": { "segments": [ { "airline": "AN_AIRLINE", "flight_number": "1234" } ] }, "return": { "segments": [ { "airline": "AN_AIRLINE", "flight_number": "1234" } ] } } }
{
"testtest" : 123
}
// Root myDeserializedClass = JsonConvert.DeserializeObject(myJsonResponse);
public class Root
{
[JsonProperty("testtest")]
public int testtest { get; set; }
}
CHECK TEST CASE # 4 Test_4_BracketError
Example :
{
"test":[
{
"Mbo":[
[
160
]
]
},
{
"Mbo":[
]
}
]
}
Should return
// Root myDeserializedClass = JsonConvert.DeserializeObject(myJsonResponse);
public class Test {
public List Mbo { get; set; }
}
public class Root {
public List<Test> Test { get; set; }
}
ADD TEST CASES
Check test case : 371d1c4
{"test" : "erground "fight clubs" f"}
As per the following references,
The new CORE 3.x/5.x JSON de-serializer uses a different JsonProperty name to the NewtonSoft one.
Thanks very much!
[JsonProperty]
.{ get; }
-only, without setters.IReadOnlyList<T>
but the ctor parameter will be typed as List<T>
.Hi
I noticed when using the tool today from this URL https://json2csharp.com/json-to-csharp that the JsonPropertyAttributes are no longer being added to the output C# Code.
This was working yesterday. I noticed that a PR/13 branch was merged in yesterday.
So with this example JSON
{
"Class1":{
"id":4,
"user_id":"user_id_value",
"created_at":"2015-06-02 23:33:90",
"updated_at":"2015-06-02 23:33:90"
}
}
I would expect to see this response:
// Root myDeserializedClass = JsonConvert.DeserializeObject<Root>(myJsonResponse);
public class Class1 {
[JsonProperty("id")]
public int Id { get; set; }
[JsonProperty("user_id")]
public string UserId { get; set; }
[JsonProperty("created_at")]
public string CreatedAt { get; set; }
[JsonProperty("updated_at")]
public string UpdatedAt { get; set; }
}
public class Root {
[JsonProperty("Class1")]
public Class1 Class1 { get; set; }
}
But what I get is this:
// Root myDeserializedClass = JsonConvert.DeserializeObject<Root>(myJsonResponse);
public class Class1 {
public int Id { get; set; }
public string UserId { get; set; }
public string CreatedAt { get; set; }
public string UpdatedAt { get; set; }
}
public class Root {
public Class1 Class1 { get; set; }
}
Thanks
connection string etc... for logging
with favorites ?
I would like to keep original properties order
{
"": ""
}
Hi I'm looking to do a F# version and was wondering if the C# version is available?
It would be nice to be able to generate nullable field members for primitive types. When serializing with JsonConvert, we can skip serializing field members that are null.
public Nullable<int> StudentId;
[
{
"prop1": "value1"
}
]
Results in:
// Root myDeserializedClass = JsonConvert.DeserializeObject(myJsonResponse);
public class MyArray {
public string prop1 { get; set; }
}
public class Root {
public List MyArray { get; set; }
}
Should be something like:
JsonConvert.DeserializeObject<List>(myJsonResponse);
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.