need some help here.
I'm not getting deserialize this json in vb.net.
I need the values lat : -21.4105261 and lng : -42.1956855.
{
"results" : [
{
"address_components" : [
{
"long_name" : "28460-000",
"short_name" : "28460-000",
"types" : [ "postal_code" ]
}
],
"formatted_address" : "Rua Francisco Cardoso, 25 - Morro do Demétrio, Miracema - RJ, 28460-000, Brazil",
"geometry" : {
"bounds" : {
"northeast" : {
"lat" : -21.4105261,
"lng" : -42.1956855
},
"southwest" : {
"lat" : -21.4105429,
"lng" : -42.1956892
}
},
"location" : {
"lat" : -21.4105429,
"lng" : -42.1956892
},
"location_type" : "RANGE_INTERPOLATED",
"viewport" : {
"northeast" : {
"lat" : -21.4091855197085,
"lng" : -42.1943383697085
},
"southwest" : {
"lat" : -21.4118834802915,
"lng" : -42.1970363302915
}
}
},
"place_id" : "ElBSdWEgRnJhbmNpc2NvIENhcmRvc28sIDI1IC0gTW9ycm8gZG8gRGVtw6l0cmlvLCBNaXJhY2VtYSAtIFJKLCAyODQ2MC0wMDAsIEJyYXNpbA",
"types" : [ "street_address" ]
}
],
"status" : "OK"
}
Can anyone help?
This is the first time I use Json so I'm not experienced with it.
Ps: I have the json.net library installed.
You can use json.net and deserialize the json.
1/ Create the model
Public Class GooglCitiesResult
Public Property city As String
Public Property country As String
Public Property country_code As String
End Class
Public Class GoogleGeoCodeResponse
Public Property status As String
Public Property results As results()
End Class
Public Class results
Public Property formatted_address As String
Public Property geometry As geometry
Public Property types As String()
Public Property address_components As address_component()
End Class
Public Class geometry
Public Property location_type As String
Public Property location As location
End Class
Public Class location
Public Property lat As String
Public Property lng As String
End Class
Public Class address_component
Public Property long_name As String
Public Property short_name As String
Public Property types As String()
End Class
2/ call it in your controller
GoogleUrl = "http://maps.google.com/maps/api/geocode/json?address=Paris,France&sensor=false&language=en"
Dim client As WebClient = New WebClient()
client.Encoding = System.Text.Encoding.UTF8
Dim result = Await client.DownloadStringTaskAsync(GoogleUrl)
Dim jsonGoogle As GoogleGeoCodeResponse = Newtonsoft.Json.JsonConvert.DeserializeObject(Of GoogleGeoCodeResponse)(result)
Dim GoogleLatitude As String = jsonGoogle.results(0).geometry.location.lat
Dim GoogleLongitude As String = jsonGoogle.results(0).geometry.location.lng
First you need to create a custom class to represent the object you are looking to deserialize.. then you would do something like...
Dim jss = New JavaScriptSerializer
Dim resp As List(Of cls_custom_class) = jss.Deserialize(Of List(Of cls_custom_class))(json)
IF you built the class properly, the Deserialize function should be able to map the JSON to your custom object and then you will have full access to whatever field/values you need.
Related
Is there any way to implement abstract validator for something like this?
public class AddOrUpdateMeasurementCommandValidator : AbstractValidator<AddOrUpdateMeasurementCommand<MainMeasurement>>
// or more precise
public class AddOrUpdateMeasurementCommandValidator<T> : AbstractValidator<AddOrUpdateMeasurementCommand<T>> where T : MainMeasurement
Model looks like this :
ChoiceMeasurement : MainMeasurement
TrueOrFalseMeasurement : MainMeasurement
TextMeasurement : MainMeasurement
public class AddOrUpdateMeasurementCommand<T> : ICommand where T : MainMeasurement
in code there is called by this :
var command = new AddOrUpdateMeasurementCommand<NumericMeasurement>
{
// values
};
_serviceTools.CommandBus.SendCommand(command);
{
"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.
I am doing a simple conversion using Jackson:
response = mapper.readValue(responseStr, PrinterStatus.class);
The code is throwing this exception:
com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "OutputParameters" (class com.xerox.PrinterStatus),
not marked as ignorable (one known property: "outputParameters"]) at ....
at com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException.from(UnrecognizedPropertyException.java:61)
at com.fasterxml.jackson.databind.DeserializationContext.handleUnknownProperty(DeserializationContext.java:823)
at com.fasterxml.jackson.databind.deser.std.StdDeserializer.handleUnknownProperty(StdDeserializer.java:1153)
at com.fasterxml.jackson.databind.deser.BeanDeserializerBase.handleUnknownProperty(BeanDeserializerBase.java:1589)
The Json I would like to convert is very simple:
{
"OutputParameters": {
"#xmlns": "http://xmlns.xerox.com/apps/rest/",
"#xmlns:xsi": "http://www.w3.org/2001/XMLSchema-instance",
"GETPRINTERSTATUS": {
"GETPRINTERSTATUS_ITEM": [{
"STATUS": "True",
"MESSAGE": " "
}]
}
}
}
This is the PrinterStatus class, it has the field "OutputParameters"
So I am not sure what is Jackson yelling about.
public class PrinterStatus {
private OutputParameters outputParameters;
public OutputParameters getOutputParameters() {
return outputParameters;
}
public void setOutputParameters(OutputParameters outputParameters) {
this.outputParameters = outputParameters;
}
...
Basically JSON keys are case sensitive. Accordingly OutputParameters doesn't equal to outputParameters.
So you have to choose:
rename the field in Java class (and getters / setters too) to OutputParameters
rename JSON property key to outputParameters
If you using Jackson 2.9 or above just simply annotate field like this:
public class PrinterStatus {
#JsonFormat(with = JsonFormat.Feature.ACCEPT_CASE_INSENSITIVE_PROPERTIES)
private OutputParameters outputParameters;
public OutputParameters getOutputParameters() {
return outputParameters;
}
public void setOutputParameters(OutputParameters outputParameters) {
this.outputParameters = outputParameters;
}
...
}
Set property name explicitly
public class PrinterStatus {
#JsonProperty("OutputParameters")
private OutputParameters outputParameters;
...
}
Enable case insesitive feature globally
ObjectMapper mapper = new ObjectMapper();
mapper.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true);
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.
I have the following classes contained by Geography.framework (a Swift framework project):
public class Contact : NSObject
{
public static let Table: String = "contacts"
public class Fields : NSObject
{
public static let Id: String = "_id"
public static let Name: String = "name"
static let rawId: String = "rawId"
}
}
public class Country : NSObject
{
public class Fields : NSObject
{
public static let Id: String = "_id"
public static let Prefix: String = "prefix"
static let rawId: String = "rawId"
}
}
In my swift app using this framework everything works smoothly:
import geography
func setFields()
{
var contactName:String = Contact.Fields.Name
var countryPrefix:String = Country.Fields.Prefix
var contactsTable: String = Country.Table
}
Well, if I use the same Geography.framework in ObjectiveC, I see Contact and Country class but the nested classes Fields are not seen. Also the value of Contact.Table is not seen.
What I need to do in order to have same library structure and library usage in ObjectiveC?
Thank you,
You have to be explicit here with definition for ObjC.
public class Country: NSObject {
#objc(CountryFields) public class Fields: NSObject {
// ...
}
}
This should expose your Switf's Country.Fields for your ObjC as CountryFields. I haven't tested it but I believe you don't have to be explicit about inheriting from NSObject. #objc attribute should do it for you when compiling.
Update for Swift 3:
Looks like this was broken in Swift 3 and won't be fixed. https://bugs.swift.org/browse/SR-2267?focusedCommentId=21033&page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel#comment-21033
You can use a trick with typealias to have the same syntax when using it :
public class Contact : NSObject
{
public static let Table: String = "contacts"
typealias Fields = ContactFields
}
#objcMembers
public class ContactFields : NSObject
{
public static let Id: String = "_id"
public static let Name: String = "name"
static let rawId: String = "rawId"
}
public class Country : NSObject
{
typealias Fields = CountryFields
}
#objcMembers
public class CountryFields : NSObject
{
public static let Id: String = "_id"
public static let Prefix: String = "prefix"
static let rawId: String = "rawId"
}