VB.Net_Having Problem with reading a token from JSON - json

I'm making a program that reads weather data from open weather map API
Here's the response(json):
coord
lon -0.1257
lat 51.5085
weather
0
id 802
main "Clouds"
description "scattered clouds"
icon "03d"
base "stations"
main
temp 22.43
feels_like 22.4
temp_min 19.82
temp_max 24.21
pressure 1021
humidity 64
visibility 10000
wind
speed 4.12
deg 270
clouds
all 40
dt 1625834363
sys
type 2
id 2006068
country "GB"
sunrise 1625802859
sunset 1625861805
timezone 3600
id 2643743
name "London"
cod 200
and here is the code I use to select tokens from json:
Imports System.Net
Imports System.IO
Imports Newtonsoft.Json.Linq
Public deg As String = Chr(176)
Public iconid As String = ""
Public locationstr As String
Public ApiKey As String = "MYAPIKEY"
#Region "Conditions"
Public windspeedMPS As String = ""
Public humidity As String = ""
Public description As String
Public cloudiness As String = ""
Public temp As String = ""
Public City As String = ""
#End Region
Public Sub getweather(ByVal key As String)
Dim req As HttpWebRequest = DirectCast(WebRequest.Create("http://api.openweathermap.org/data/2.5/weather?q=" & locationstr & "&appid=" & ApiKey & "&lang=en&units=metric"), HttpWebRequest)
Dim res As HttpWebResponse = DirectCast(req.GetResponse, HttpWebResponse)
Dim reader As New StreamReader(res.GetResponseStream)
Dim serverresponse As String = reader.ReadToEnd
Dim json As String = serverresponse
Dim obj As JObject = JObject.Parse(json)
Try
windspeddMPS = obj.SelectToken("wind").SelectToken("speed")
humidity = obj.SelectToken("main").SelectToken("humidity")
description = obj.SelectToken("weather").SelectToken("description")
cloudiness = obj.SelectToken("clouds").SelectToken("all")
temp = obj.SelectToken("main").SelectToken("temp")
City = obj.SelectToken("name")
iconid = obj.SelectToken("weather").SelectToken("icon")
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
I can select all the tokens except "description"(weather condition within a group) and "icon"(weather condition icon id) tokens.

For reference, here is the documentation for the web API you're using: https://openweathermap.org/current
Visual Studio has a cool feature called Paste JSON as Classes that can be found under Edit > Paste Special > Paste JSON as Classes. If you were to do this, then you would get something that looks like the following:
Public Class Rootobject
Public Property coord As Coord
Public Property weather() As Weather
Public Property base As String
Public Property main As Main
Public Property visibility As Integer
Public Property wind As Wind
Public Property clouds As Clouds
Public Property dt As Integer
Public Property sys As Sys
Public Property timezone As Integer
Public Property id As Integer
Public Property name As String
Public Property cod As Integer
End Class
Public Class Coord
Public Property lon As Single
Public Property lat As Single
End Class
Public Class Main
Public Property temp As Single
Public Property feels_like As Single
Public Property temp_min As Single
Public Property temp_max As Single
Public Property pressure As Integer
Public Property humidity As Integer
End Class
Public Class Wind
Public Property speed As Single
Public Property deg As Integer
End Class
Public Class Clouds
Public Property all As Integer
End Class
Public Class Sys
Public Property type As Integer
Public Property id As Integer
Public Property message As Single
Public Property country As String
Public Property sunrise As Integer
Public Property sunset As Integer
End Class
Public Class Weather
Public Property id As Integer
Public Property main As String
Public Property description As String
Public Property icon As String
End Class
From here, you can deserialize the JSON response to the Rootobject class which in turn you have access to strongly typed objects to get your values:
' ... HTTP request to get JSON
Dim jsonObject = JsonConvert.DeserializeObject(Of Rootobject)(json)
Console.WriteLine(jsonObject.clouds.all)

Related

Extract data from a JSON received from an HTTP response

So I have an HTTP response that gives me this data:
{
"result":"success",
"records":{
"509442013":{
"nif":509442013,
"seo_url":"nexperience-lda",
"title":"Nexperience Lda",
"address":"Rua da Lionesa Nº 446, Edifício G20",
"pc4":"4465",
"pc3":"671",
"city":"Leça do Balio",
"activity":"Desenvolvimento de software. Consultoria em informática. Comércio de equipamentos e sistemas informáticos. Exploração de portais web.",
"status":"active",
"cae":"62010",
"contacts":{
"email":"info#nex.pt",
"phone":"220198228",
"website":"www.nex.pt",
"fax":"224 905 459"
},
"structure":{
"nature":"LDA",
"capital":"5000.00",
"capital_currency":"EUR"
},
"geo":{
"region":"Porto",
"county":"Matosinhos",
"parish":"Leça do Balio"
},
"place":{
"address":"Rua da Lionesa Nº 446, Edifício G20",
"pc4":"4465",
"pc3":"671",
"city":"Leça do Balio"
},
"racius":"http://www.racius.com/nexperience-lda/",
"alias":"Nex - Nexperience, Lda",
"portugalio":"http://www.portugalio.com/nex/"
}
},
"nif_validation":true,
"is_nif":true,
"credits":{
"used":"free",
"left":[
]
}
}
And I need to extract some data from it, like the fields:
NIF
title
and the email and phone that are inside the contacts array.
I need the data to populate some TextBoxes in my Form.
To get the http response I have this button but I don't know how to extract the data I need.
Can someone help me?
My code:
Private Sub Btn_NIFImport_Click(sender As Object, e As EventArgs) Handles Btn_NIFImport.Click
Dim key As String = "xxxxxxxxxxxxxxxxxxxxxxxxxx"
Try
'Create the request
Dim request As HttpWebRequest = HttpWebRequest.Create("http://www.nif.pt/?json=1&q=" & Txt_NIFImport.Text & "&key=" & key)
request.Proxy = Nothing
request.UserAgent = "Test"
'Create the response reader
Dim response As HttpWebResponse = request.GetResponse
Dim responseStream As System.IO.Stream = response.GetResponseStream
'Create a new stream reader
Dim streamReader As New System.IO.StreamReader(responseStream)
Dim data As String = streamReader.ReadToEnd
streamReader.Close()
'Display the data on the screen
Txt_Teste.Text = data
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
Thanks in advance.
after you get the response from the http request you need to deserialize the json to an object in vb.net
To Classes to create the object by your json:
Public Class [Structure]
Public Property nature As String
Public Property capital As String
Public Property capital_currency As String
End Class
Public Class Geo
Public Property region As String
Public Property county As String
Public Property parish As String
End Class
Public Class Place
Public Property address As String
Public Property pc4 As String
Public Property pc3 As String
Public Property city As String
End Class
Public Class Record
Public Property nif As Integer
Public Property seo_url As String
Public Property title As String
Public Property address As String
Public Property pc4 As String
Public Property pc3 As String
Public Property city As String
Public Property activity As String
Public Property status As String
Public Property cae As String
Public Property contacts As Contacts
Public Property [structure] As [Structure]
Public Property geo As Geo
Public Property place As Place
Public Property racius As String
Public Property [alias] As String
Public Property portugalio As String
End Class
Public Class Credits
Public Property used As String
Public Property left As List(Of Object)
End Class
Public Class Root
Public Property result As String
Public Property records As Dictionary(Of String, Record)
Public Property nif_validation As Boolean
Public Property is_nif As Boolean
Public Property credits As Credits
End Class
and to deserialize added after you get the response the following line:
Root l = JsonConvert.DeserializeObject<Root>(response);
EDIT:
I made some changes in the code so now you use with Dictionary that has KEY in your json '509442013' and value As Record (Notice that I change the class name as was before '_509442013')
And in the root changes
Public Property records As Dictionary(Of String, Record)
now this will work in each time even if you will get in each http request ID as class that not the same.
notice that the only way you can get the value is by the KEY you already pass in the http request.
Added GIF:
(In my case I change the ID and city, in the result show the city from the json)
Convert Button:
Dim jsonString As String = tbInput.Text
Dim l As Root = JsonConvert.DeserializeObject(Of Root)(jsonString)
tbResult.Text = l.records(tbKEY.Text.ToString).city.ToString()
tbKEY get the value from the screen like in my gif example.

how can I parse the google books api and access the class properties (vb.net)

I'm trying to access Googles book api and just populate textboxes with the information.
Here's an example of the API json: [https://www.googleapis.com/books/v1/volumes?q=isbn:9780979799006]
I used Visual Studio's Paste Special to create the Class. Here it is:
Public Class GoogleBookData
Public Class Rootobject
Public Property kind As String
Public Property totalItems As Integer
Public Property items() As Item
End Class
Public Class Item
Public Property kind As String
Public Property id As String
Public Property etag As String
Public Property selfLink As String
Public Property volumeInfo As Volumeinfo
Public Property saleInfo As Saleinfo
Public Property accessInfo As Accessinfo
Public Property searchInfo As Searchinfo
End Class
Public Class Volumeinfo
Public Property title As String
Public Property subtitle As String
Public Property publishedDate As String
Public Property description As String
Public Property industryIdentifiers() As Industryidentifier
Public Property readingModes As Readingmodes
Public Property pageCount As Integer
Public Property printType As String
Public Property categories() As String
Public Property maturityRating As String
Public Property allowAnonLogging As Boolean
Public Property contentVersion As String
Public Property panelizationSummary As Panelizationsummary
Public Property imageLinks As Imagelinks
Public Property language As String
Public Property previewLink As String
Public Property infoLink As String
Public Property canonicalVolumeLink As String
End Class
Public Class Readingmodes
Public Property text As Boolean
Public Property image As Boolean
End Class
Public Class Panelizationsummary
Public Property containsEpubBubbles As Boolean
Public Property containsImageBubbles As Boolean
End Class
Public Class Imagelinks
Public Property smallThumbnail As String
Public Property thumbnail As String
End Class
Public Class Industryidentifier
Public Property type As String
Public Property identifier As String
End Class
Public Class Saleinfo
Public Property country As String
Public Property saleability As String
Public Property isEbook As Boolean
End Class
Public Class Accessinfo
Public Property country As String
Public Property viewability As String
Public Property embeddable As Boolean
Public Property publicDomain As Boolean
Public Property textToSpeechPermission As String
Public Property epub As Epub
Public Property pdf As Pdf
Public Property webReaderLink As String
Public Property accessViewStatus As String
Public Property quoteSharingAllowed As Boolean
End Class
Public Class Epub
Public Property isAvailable As Boolean
End Class
Public Class Pdf
Public Property isAvailable As Boolean
End Class
Public Class Searchinfo
Public Property textSnippet As String
End Class
End Class
I call this function to read the stream and get the Class data:
Public Shared Function getGoogleBookData(ByVal sSku As String) As GoogleBookData
Dim result As String = Nothing
Dim url As String = "https://www.googleapis.com/books/v1/volumes?q=isbn:"
url &= sSku
Dim request As HttpWebRequest = WebRequest.Create(url)
Dim response As HttpWebResponse = Nothing
Dim reader As StreamReader = Nothing
Dim myJson As String = Nothing
response = DirectCast(request.GetResponse(), HttpWebResponse)
reader = New StreamReader(response.GetResponseStream())
myJson = reader.ReadToEnd
Dim serializer As New System.Web.Script.Serialization.JavaScriptSerializer()
Dim myGBookData As New GoogleBookData
myGBookData = serializer.Deserialize(Of GoogleBookData)(myJson)
Return myGBookData
End Function
I call the function:
Dim gsSearchSku as String = "9780979799006"
Dim myGItem As New GoogleBookData
myGItem = getGoogleBookData(gsSearchSku)
Then, I've tried several things to try to access any data in the Class:
I know this doesn't work but put it here so you can get an idea of what I'm trying.
Dim sTitle as String = myGItem.Item.Title
I can't even run it. GoogleBookData.item is a class type and cannot be used as an expression.
No idea where to go from here.
Any help would be greatly appreciated!!

How To Deserialize JSON in vb,net with Multiple objects

Below is a json file that needs to be deserialized and to be stored in different variables.
With this current json, which is returned by an API, I am unable to deserialize because it gives me and error -
Please help me on deserializing this particular json
I have added the code i used, but it returns wrong values and null reference.
{
"result": {
"candidates": [
{
"similarity": 0.1330482513,
"person_id": "75741ea3-4d9b-4e25-8460-16444ee39946",
"descriptor_id": "2f228007-350e-4d58-9897-4b62e9978081",
"user_data": "Без названия (9)",
"external_id": null
}
],
"face": {
"id": "a1b224a3-60c6-4733-9bbc-136d53ea011c",
"score": 0.9320185781
}
},
"timestamp": 1569957900.1488559,
"source": "search",
"event_type": "match",
"authorization": {
"token_id": "71f9b3e0-51b1-480f-93b9-0e76e260bcbc",
"token_data": "first token"
},
"template": {
"descriptor_id": "a1b224a3-60c6-4733-9bbc-136d53ea011c"
},
"candidate": {
"list_id": "6e64e600-cd77-4894-940e-6f7022d8aba8",
"list_data": "FaceStream_search_list(DON'T DELETE)",
"list_type": 1
}
}
I have tried :
Public Class Rootobject
Public Property result As Result
Public Property timestamp As Single
Public Property source As String
Public Property event_type As String
Public Property authorization As Authorization
Public Property template As Template
Public Property candidate As Candidate1
End Class
Public Class Result
Public Property candidates() As Candidate
Public Property face As Face
End Class
Public Class Face
Public Property id As String
Public Property score As Single
End Class
Public Class Candidate
Public Property similarity As Double
Public Property person_id As String
Public Property descriptor_id As String
Public Property user_data As String
Public Property external_id As Object
End Class
Public Class Authorization
Public Property token_id As String
Public Property token_data As String
End Class
Public Class template
Public Property descriptor_id As String
End Class
Public Class Candidate1
Public Property list_id As String
Public Property list_data As String
Public Property list_type As Integer
End Class
''And used
Dim Candidatess As New Candidate
Candidatess = Newtonsoft.Json.JsonConvert.DeserializeObject(Of Candidate)((JObject.Parse(e.Message)).ToString)
msg(Candidatess.similarity.ToString)
msg(Candidatess.descriptor_id.ToString)
msg(Candidatess.person_id.ToString)
''REturns me Null
Public Class Candidate
Public Property similarity As Double
Public Property person_id As String
Public Property descriptor_id As String
Public Property user_data As String
Public Property external_id As Object
End Class
Public Class Face
Public Property id As String
Public Property score As Double
End Class
Public Class Result
Public Property candidates As Candidate()
Public Property face As Face
End Class
Public Class Authorization
Public Property token_id As String
Public Property token_data As String
End Class
Public Class Template
Public Property descriptor_id As String
End Class
Public Class Candidate
Public Property list_id As String
Public Property list_data As String
Public Property list_type As Integer
End Class
Public Class Candidates
Public Property result As Result
Public Property timestamp As Double
Public Property source As String
Public Property event_type As String
Public Property authorization As Authorization
Public Property template As Template
Public Property candidate As Candidate
End Class
Public Function GetData(ApiEndpoint As Uri, ApiToken As String)
Dim origResponse As HttpWebResponse = Nothing
Dim objResponse As HttpWebResponse = Nothing
Dim origReader As StreamReader = Nothing
Dim objReader As StreamReader = Nothing
Dim origRequest As HttpWebRequest = DirectCast(HttpWebRequest.Create(ApiEndpoint), HttpWebRequest)
origRequest.Headers.Add("Authorization", "Basic " & ApiToken)
origRequest.AllowAutoRedirect = False
origRequest.Method = "GET"
'Call the API and get the JSON Response data
origResponse = DirectCast(origRequest.GetResponse(), HttpWebResponse)
Dim Stream As Stream = origResponse.GetResponseStream()
Dim sr As New StreamReader(Stream, Encoding.GetEncoding("utf-8"))
Dim myJsonResponse As String = sr.ReadToEnd()
'Deserialize the Json
Dim objFormResults As Result = JsonConvert.DeserializeObject(Of Result)(myJsonResponse)
'loop through the results
End Function

How do you parse this JSON data?

I have this JSON data that I would like to parse but I'm not sure how to go about it.
Here's the JSON:
{
"input":{
"lat":32.761125,
"lon":-96.791339
},
"results":[
{
"block_fips":"481130204001105",
"bbox":[
-96.79587,
32.753273,
-96.787714,
32.76218
],
"county_fips":"48113",
"county_name":"Dallas",
"state_fips":"48",
"state_code":"TX",
"state_name":"Texas",
"block_pop_2015":2,
"amt":"AMT004",
"bea":"BEA127",
"bta":"BTA101",
"cma":"CMA009",
"eag":"EAG005",
"ivm":"IVM009",
"mea":"MEA032",
"mta":"MTA007",
"pea":"PEA008",
"rea":"REA005",
"rpc":"RPC004",
"vpc":"VPC004"
}
]
}
I used the Visual Studio tool, Edit -> Paste Special -> Paste as JSON classes, to convert this JSON in classes and it gave me this class structure:
Public Class Rootobject
Public Property input As Input
Public Property results() As Result
End Class
Public Class Input
Public Property lat As Single
Public Property lon As Single
End Class
Public Class Result
Public Property block_fips As String
Public Property bbox() As Single
Public Property county_fips As String
Public Property county_name As String
Public Property state_fips As String
Public Property state_code As String
Public Property state_name As String
Public Property block_pop_2015 As Integer
Public Property amt As String
Public Property bea As String
Public Property bta As String
Public Property cma As String
Public Property eag As String
Public Property ivm As String
Public Property mea As String
Public Property mta As String
Public Property pea As String
Public Property rea As String
Public Property rpc As String
Public Property vpc As String
End Class
So then what I did to try and parse the data is:
Dim MyJSON As String = JsonAbove
Dim jss As New JavaScriptSerializer()
Dim dict = jss.Deserialize(Of Result)(rawresp)
MsgBox(dict.state_name)
All I get is a blank MessageBox with no results.
Am I doing something wrong?
Use List Of Objects instead of array in your class. I have done two changes One in the rootobject for results and other in the result class for bbox
Public Class Rootobject
Public Property input As Input
Public Property results As List(Of Result)
End Class
Public Class Input
Public Property lat As Single
Public Property lon As Single
End Class
Public Class Result
Public Property block_fips As String
Public Property bbox As List(Of Single)
Public Property county_fips As String
Public Property county_name As String
Public Property state_fips As String
Public Property state_code As String
Public Property state_name As String
Public Property block_pop_2015 As Integer
Public Property amt As String
Public Property bea As String
Public Property bta As String
Public Property cma As String
Public Property eag As String
Public Property ivm As String
Public Property mea As String
Public Property mta As String
Public Property pea As String
Public Property rea As String
Public Property rpc As String
Public Property vpc As String
End Class
Then access the properties
Dim jss As New JavaScriptSerializer()
Dim dict = jss.Deserialize(Of Rootobject)(MyJSON)
MsgBox(dict.results.FirstOrDefault().state_name)
Same, using the Newtonsoft.Json namespace.
The classes properties have being assigned new names, using a <JsonProperty> attribute.
Also, the Results property is modified to return a List(Of Result).
The deserialization is pretty simple and straightforward:
You can use the Visual Studio NuGet Package Manager to install Newtonsoft.Json.
Imports Newtonsoft.Json
Dim latlonResults As RootObject = JsonConvert.DeserializeObject(Of RootObject)(JSON)
Dim state As String = latlonResults.Results(0).StateName
or access a property directly while deserializing:
Dim state As String = JsonConvert.DeserializeObject(Of RootObject)(JSON).Results(0).StateName
Refactored classes:
Public Class RootObject
<JsonProperty("input")>
Public Property Input() As Input
<JsonProperty("results")>
Public Property Results() As List(Of Result)
End Class
Public Class Input
<JsonProperty("lat")>
Public Property Lat() As Double
<JsonProperty("lon")>
Public Property Lon() As Double
End Class
Public Class Result
<JsonProperty("block_fips")>
Public Property BlockFips() As String
<JsonProperty("bbox")>
Public Property Bbox() As List(Of Double)
<JsonProperty("county_fips")>
Public Property CountyFips() As Long
<JsonProperty("county_name")>
Public Property CountyName() As String
<JsonProperty("state_fips")>
Public Property StateFips() As Long
<JsonProperty("state_code")>
Public Property StateCode() As String
<JsonProperty("state_name")>
Public Property StateName() As String
<JsonProperty("block_pop_2015")>
Public Property BlockPop2015() As Long
<JsonProperty("amt")>
Public Property Amt() As String
<JsonProperty("bea")>
Public Property Bea() As String
<JsonProperty("bta")>
Public Property Bta() As String
<JsonProperty("cma")>
Public Property Cma() As String
<JsonProperty("eag")>
Public Property Eag() As String
<JsonProperty("ivm")>
Public Property Ivm() As String
<JsonProperty("mea")>
Public Property Mea() As String
<JsonProperty("mta")>
Public Property Mta() As String
<JsonProperty("pea")>
Public Property Pea() As String
<JsonProperty("rea")>
Public Property Rea() As String
<JsonProperty("rpc")>
Public Property Rpc() As String
<JsonProperty("vpc")>
Public Property Vpc() As String
End Class

JSON <NonSerialized()> not working VB.NET?

I'm having a bit of trouble with some JSON serialization that I'm doing in VB.NET.
Basically, I have two classes.
MenuItemDataLong
And MenuItemDataShort
MenuItemDataLong inherits MenuItemDataShort.
Code:
MenuItemDataShort.vb
<Serializable()>
Public Class MenuItemDataShort
Public Display_Name As String = ""
Public Display_Description As String = ""
Public Display_Price As Single = 0.0
Public SELECTED_NAME As Integer = 0
Public SELECTED_PRICE As Integer = 0
Public WEB_IMAGE As String = ""
Public WEB_IMAGE_WIDTH As Integer = 0
Public WEB_IMAGE_HEIGHT As Integer = 0
Public PAGE_NUM As Integer = 0
Public CELL_ID As Integer = 0
Public SHOW_BMP_FILE As Boolean = False
Public SHOW_DESCRIPT As Boolean = False
Public SHOW_PRICE As Boolean = False
Public SHOW_LONG_DESC As Boolean = False
Public LONG_DESC_FONT_NAME As String
Public LONG_DESC_FONT_BOLD As Boolean
Public LONG_DESC_FONT_UNDERLINE As Boolean
Public LONG_DESC_FONT_ITALIC As Boolean
Public LONG_DESC_FONT_COLOR_R As Integer
Public LONG_DESC_FONT_COLOR_G As Integer
Public LONG_DESC_FONT_COLOR_B As Integer
Public LONG_DESC_FONT_SIZE As Integer
Public DESC_FONT_NAME As String
Public DESC_FONT_BOLD As Boolean
Public DESC_FONT_UNDERLINE As Boolean
Public DESC_FONT_ITALIC As Boolean
Public DESC_FONT_COLOR_R As Integer
Public DESC_FONT_COLOR_G As Integer
Public DESC_FONT_COLOR_B As Integer
Public DESC_FONT_SIZE As Integer
Public PRICE_FONT_NAME As String
Public PRICE_FONT_BOLD As Boolean
Public PRICE_FONT_UNDERLINE As Boolean
Public PRICE_FONT_ITALIC As Boolean
Public PRICE_FONT_COLOR_R As Integer
Public PRICE_FONT_COLOR_G As Integer
Public PRICE_FONT_COLOR_B As Integer
Public PRICE_FONT_SIZE As Integer
Public DESC_X As Integer
Public DESC_Y As Integer
Public PRICE_X As Integer
Public PRICE_Y As Integer
Public IMAGE_X As Integer
Public IMAGE_Y As Integer
Public LONG_DESC_X As Integer
Public LONG_DESC_Y As Integer
End Class
MenuItemDataLong.vb
<Serializable()>
Public Class MenuItemDataLong
Inherits MenuItemDataShort
<NonSerialized()>
Public DESCRIPT As String
<NonSerialized()>
Public OO_Alias As String
<NonSerialized()>
Public LONG_DESCRIPTION As String
<NonSerialized()>
Public RECIPE_DESCRIPTION As String
<NonSerialized()>
Public BMP_FILE As String
<NonSerialized()>
Public PRICE1, PRICE2, PRICE3, PRICE4, PRICE5, PRICE6, PRICE7, PRICE8, PRICE9, PRICE10, PRICE11, PRICE12, PRICE13, PRICE14 As Single
End Class
I then have the MenuItemDataLong object stored somewhere. The excess data in the MenuItemDataLong class is necessary in application, but is not necessary once the file is serialized. So, I'm trying to take the MenuItemDataLong and cast it back down to a MenuItemDataShort and serialize it. However, Whenever I do I end up with all of the data from MenuItemDataLong still in it, even with the NonSerialized() tags.
Anyone know what I'm doing wrong?..
EDIT:
If anyone is curious, this is how I'm serializing:
Dim sItemData As MenuItemDataShort = CType(ItemData, MenuItemDataShort)
Dim Serializer As New System.Web.Script.Serialization.JavaScriptSerializer
Dim Serialized As String = Serializer.Serialize(sItemData)
You are basically using the wrong attribute. From MSDN - NonSerialized:
When using the BinaryFormatter or SoapFormatter classes to serialize an object, use the NonSerializedAttribute attribute to prevent a field from being serialized.
It does not mention the JavaScriptSerializer. There is another attribute: <ScriptIgnore> which seems to work. Using simplified classes and a mix of actual Properties and Fields:
Imports System.Web.Script.Serialization
<Serializable()>
Public Class MenuItemShort
Public Property Name As String = ""
Public Description As String = ""
End Class
<Serializable()>
Public Class MenuItemLong
Inherits MenuItemShort
<ScriptIgnore>
Public Property Foo As String
<ScriptIgnore>
Public Bar As String
Public Property Value As Integer
End Class
Test Code:
Dim mi As New MenuItemLong With {.Name = "foo",
.Description = "a foo item",
.Foo = "ghost in the machine",
.Bar = "bar",
.Value = 42}
Dim miS As MenuItemShort = DirectCast(mi, MenuItemShort)
Dim jser As New System.Web.Script.Serialization.JavaScriptSerializer
Dim jss As String = jser.Serialize(miS)
Console.WriteLine(jss)
Output:
{"Description":"a foo item","Value":42,"Name":"foo"}
There are other ways to ignore certain properties using NewtonSoft's JSON.Net.