What is an efficient way to generate vb classes from json schemas? - vb.net

Is there any way to generate vb classes from jsonschema files like we can generate classes from wsdls and xsds using wsdl.exe in one go.
I don't want to use Edit > Paste special > paste JSON as class feature of Visual Studio because I tried for one file and it did not give me the result I am expecting and also there are about 15 schema files so want a generic way.
On using Edit > Paste special > paste JSON as class feature of Visual Studio,
The schema have is:
{
"title": "MyObject",
"type": "object",
"properties": {
"description": {
"type": "string"
},
"name": {
"type": "string"
},
"id": {
"type": "string"
}
},
"required": [ "id", "description", "name" ]
}
The generated classes:
Public Class Rootobject
Public Property title As String
Public Property type As String
Public Property properties As Properties
Public Property required() As String
End Class
Public Class Properties
Public Property description As Description
Public Property name As Name
Public Property id As Id
End Class
Public Class Description
Public Property type As String
End Class
Public Class Name
Public Property type As String
End Class
Public Class Id
Public Property type As String
End Class

Related

How to parse this json with newtonsoft?

{
"boxes": [
{
"hash": "51532859",
"owner": "9",
"id": "3868",
"isDisabled": false
"innerbox": {
"color": "aaaa",
"size": "bbbb"
}
},
{
"hash": "cccc",
"owner": "9",
"id": "3868",
"isDisabled": false
"innerbox": {
"color": "cccc",
"size": "dddd"
}
}
],
"meta": {
"currencies": {
"USD": {
"total": "2",
"value": "123456",
"currency": "USD",
"isDisabled": false
}
},
"total": 2
}
}
Above is the JSON (I've cut it down and replaced some info, but its the same format) that I retrieve from a web server. I am trying to use NewtonSoft JSON to Deserialize it but I am getting an error "because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly."
Here is my class:
Public Class TheBox
Public Property boxes() As Boxes
Public Property meta As Meta
Public Property usd As USD
Public Property innerbox As InnerBox
End Class
Public Class Meta
Public Property currencies As Currencies
Public Property total As Integer
End Class
Public Class Currencies
Public Property USD As USD
End Class
Public Class USD
Public Property total As String
Public Property value As String
Public Property currency As String
Public Property isDisabled As Boolean
End Class
Public Class Boxes
Public Property hash As String
Public Property owner As String
Public Property id As String
Public Property isDisabled As Boolean
End Class
Public Class InnerBox
Public Property color As String
Public Property size As String
End Class
This is how I am trying to Deserialize it:
Dim obj = JsonConvert.DeserializeObject(Of TheBox)(Json)
Any help is appreciated, thank you
Your current json as posted looks to be "bad" or malformed.
So, this:
"isDisabled": false
"innerbox": {
"color": "aaaa",
"size": "bbbb"
}
There is a comma (",") missing after the false.
so, it needs to be:
"isDisabled": false,
"innerbox": {
"color": "aaaa",
"size": "bbbb"
}
Same for the one further down.
Once you fix those two issues, then this json will and should parse just fine.
You can have Visual Studio create the classes for you like this:
Create a blank new class, and then ctrl-a and del key to empty out. Then this:
And now VS spits out this:
Public Class Rootobject
Public Property boxes() As Box
Public Property meta As Meta
End Class
Public Class Meta
Public Property currencies As Currencies
Public Property total As Integer
End Class
Public Class Currencies
Public Property USD As USD
End Class
Public Class USD
Public Property total As String
Public Property value As String
Public Property currency As String
Public Property isDisabled As Boolean
End Class
Public Class Box
Public Property hash As String
Public Property owner As String
Public Property id As String
Public Property isDisabled As Boolean
Public Property innerbox As Innerbox
End Class
Public Class Innerbox
Public Property color As String
Public Property size As String
End Class
So, the top most root item here is Root object - you can re-name that if you wish.
I not test above with the above data sample (first fix it), but I'm going for a coffee - if I have time, I will give your data a try with above code later.

Handle Serialization and Deserialization with json schema using jsonschema2pojo

I have below json schema and generated java class using jsonschema2pojo library
AddressSchema.json
{
"$id": "https://example.com/address.schema.json",
"$schema": "http://json-schema.org/draft-07/schema#",
"description": "An address similar to http://microformats.org/wiki/h-card",
"type": "object",
"properties": {
"address": {
"type": "string"
}
}
AddressSchema.java
public class AddressSchema {
private String address;
#JsonProperty("address")
public String getAddress() {
return address;
}
#JsonProperty("address")
public void setAddress(String address) {
this.address = address;
}
}
My requirement is to generate class with different values in #JsonProperty on setter and getter like below. Is there any way to achieve this behavior?
public class AddressSchema {
private String address;
#JsonProperty("address")
public String getAddress() {
return address;
}
#JsonProperty("addr") //different value in the setter
public void setAddress(String address) {
this.address = address;
}
}
I believe you are trying to use the same class to parse a certain json with different name addr and have it return with different name address. I don't see how it might be possible without using two classes and a mapper to map the values. As humans we'd think address and addr are pretty similar and there must be mechanisms to map them while address and name are totally different I wouldn't ask for them to be mapped. But for computers it would be a difficult feature to provide. Hope you get my point.

Deserializing "Unwrapped" Json Arrays to POJO

Half of my problem is not knowing the exact terms to search for an answer. I believe I'm dealing with what's called a "flat" or "unwrapped" json array with the underlying "members" node in that this would work if there was a "member:" element for each of the "members" underlying property nodes, but there isn't.
I receive json (I can't control format) that looks like this:
{
"id" : "1",
"context" :
{
"id" : "123,
"title" : "My Title"
},
"members": [
{
"prop1" : { },
"prop2" : "123",
"propArray1" : [ "Value1", "Value2" ],
"prop3" : "xyz",
"prop4" : "123"
},
{
"prop1" : { },
"prop2" : "456",
"propArray1" : [ "Value1", "Value2" ],
"prop3" : "abc",
"prop4" : "456"
}
] }
My POJO (minus the simple gets/sets):
#JsonAutoDetect
public class MyPojo {
#JsonProperty
private String id;
#JsonProperty
private Context context;
#JsonProperty("members")
private List<Member> members = new ArrayList<>();
#JsonAutoDetect
public class Context {
public Context() {}
#JsonProperty
private String id;
#JsonProperty
private String title;
}
#JsonAutoDetect
public class Member {
public Member() {}
#JsonProperty
private String prop1;
#JsonProperty
private String prop2;
#JsonProperty
private List<String> propArray1 = new ArrayList<>();
#JsonProperty
private String prop3;
#JsonProperty
private String prop4;
#JsonProperty
private String prop5;
}
public List<Member> getMembers() {
return members;
}
public void setMembers(List<Member> members) {
this.members = members;
}
}
I've tried GSON:
new Gson().fromJson(jsonEntity, MyPojo.class);
returns:
java.lang.IllegalStateException: Expected a string but was BEGIN_OBJECT
I've tried Jackson:
new ObjectMapper().readValue(jsonEntity, MyPojo.class);
throws:
org.codehaus.jackson.map.JsonMappingException: No suitable constructor found for type [simple type, class MyPojo$Member]: can not instantiate from JSON object (need to add/enable type information?)
at [Source: java.io.StringReader#5c6e5b53; line: 10, column: 3] (through reference chain: MyPojo["members"])
I don't think "add/enable" type information is a relevant warning and I do have the default constructor.
I've searched dozens of json deserialization posts and this one seems similar to this but I have to get the entire Json object not just a piece of it...and I tried it just to extract members array and it didn't work.
Cannot deserialize JSON to POJO
there are some issues here:
the JSON testdata is not valid (missing closing " at second id). corrected version:
{
"id" : "1",
"context" :
{
"id" : "123",
"title" : "My Title"
},
"members": [
{
"prop1" : { },
"prop2" : "123",
"propArray1" : [ "Value1", "Value2" ],
"prop3" : "xyz",
"prop4" : "123"
},
{
"prop1" : { },
"prop2" : "456",
"propArray1" : [ "Value1", "Value2" ],
"prop3" : "abc",
"prop4" : "456"
}
] }
second issue: nested classes by default have a reference to the enclosing class. one consequence of this is that they cannot be created without an instance of the enclosing class. Jackson i get this exception:
Cannot construct instance of `foo.MyPojo$Member` (although at least one Creator exists)
fix this by converting the nested classes to static inner classes:
public static class Context {
...
}
third issue: the mapping does not match the JSON.
Cannot deserialize instance of `java.lang.String` out of START_OBJECT token
...
(through reference chain: foo.MyPojo["members"]->java.util.ArrayList[0]->foo.MyPojo$Member["prop1"])
fix this by changing the mapping. e.g:
#JsonAutoDetect
public static class Member {
public Member() {}
#JsonProperty
private Map<String, String> prop1;
...
}
Using this 3 changes its possible to deserialize the JSON using Jackson.

Read DropBox info.json file with .NetJSON

Any ideas, I don't understand the Object I need to define. I am coding in VB but C# is OK. The file is one line but seems to have some nesting with Personal and Business.
{
"personal": {
"path": "C:\\Users\\Paul\\Dropbox (Personal)",
"host": 4897400149,
"is_team": false,
"subscription_type": "Basic"
},
"business": {
"path": "C:\\Users\\Paul\\Dropbox (Y2016)",
"host": 4897401185,
"is_team": true,
"subscription_type": "Business"
}
}
You can define your classes as follows:
Public Class DropBoxFolderPath
Public Property path As String
Public Property host As Long
Public Property is_team As Boolean
Public Property subscription_type As String
End Class
Public Class DropBoxFolderPaths
Public Property personal As DropBoxFolderPath
Public Property business As DropBoxFolderPath
End Class
Then deserialize as follows:
Dim dropBoxFolders = JsonConvert.DeserializeObject(Of DropBoxFolderPaths)(jsonString)
Example fiddle. Related documentation: How can I programmatically find the Dropbox folder paths?.

Data annotations in Swagger

I am using ASP.NET and Swagger that exposes a complex type that accepts a POST. It has a number of string fields that have different restricted lengths. How can I reflect that in the Swagger UI?
You can annotate the properties with the StringLengthAttribute from System.ComponentModel.DataAnnotations.
For instance:
[StringLength(10)]
public String Name {get;set;}
will become:
"name": {
"minLength": 0,
"maxLength": 10,
"type": "string"
}
And this:
[StringLength(10, MinimumLength = 5)]
public String Name {get;set;}
becomes:
"name": {
"minLength": 5,
"maxLength": 10,
"type": "string"
}
Besides StringLength Swashbuckle also supports the Range and RegularExpression attributes.
Update
MaxLength does not work. StringLength does. However, discovering this information in Swagger UI is a bit clumsy. You have to navigate to the Model of your object and then hover over the property: