Serialise list of objects to single JSON object, with property as key:value - json.net

Public Class Doc
Public TypeDoc As String = ""
Public Property UserFields As New List(Of UserField)
End Class
Public Class UserField
Property Name As String = ""
Property Value As String = ""
End Class
Public Class Example
Public Sub test()
Dim d As New Doc
d.TypeDoc = "Order"
d.UserFields.Add(New UserField With {.Name = "U_Name", .Value = "Jonny"})
d.UserFields.Add(New UserField With {.Name = "U_Surname", .Value = "Goodman"})
Dim Ret As String = JsonConvert.SerializeObject(d)
End Sub
End Class
Desired result "Ret":
{
"TypeDoc": "Order",
"U_Name": "Jonny",
"U_Surname": "Goodman",
}
I hope you understand the example, I was wondering if it was possible to have this result.
Thank you

Related

Calling and serializing FB feed

I am calling FB feed from multiple FB pages with
/posts?ids=OI.Plavipingvin,217384491624554&limit=5&fields=message,created_time,id
This is the feed I get:
{
"217384491624554": {
"data": [
{
"message": "Obećanje i zavjet položeni. Dobrodošli u OI Javor ❤",
"created_time": "2017-01-08T01:05:25+0000",
"id": "217384491624554_1575515795811410"
},
{
"message": "Zimovanje u punom tijeku :-)",
"created_time": "2017-01-04T10:06:57+0000",
"id": "217384491624554_1572127976150192"
}
],
"paging": {
"previous": "https://graph.facebook.com/v2.8/217384491624554/posts?fields=message,created_time,id&limit=2&format=json&since=1483837525&access_token=EAACEdEose0cBAMlhIYetCMo0m83Jdo3F7rk4NYmm47Q1T19UDxlKhMQnjDW4Mmelqu3vzTITnVA7E0ZBgl6jDmlHC8J7ZCX4TW2xB0xoHIySu3MK5d9yUWjqMLdUrRab9KTfH1WyzpEfIbxG7JlhPnZACfiFWFfhvO9vrAZCrAZDZD&__paging_token=enc_AdB6GEshkXkXuRJcuiHCF1aoS4rK7Myp3P6mFZAUFeZAPbRVdtmihE7UAOIlFDuTjVKHvmBeiMLmWfIZBfCER7cYrS08kccUDDoixEb2ZABASuwAigZDZD&__previous=1",
"next": "https://graph.facebook.com/v2.8/217384491624554/posts?fields=message,created_time,id&limit=2&format=json&access_token=EAACEdEose0cBAMlhIYetCMo0m83Jdo3F7rk4NYmm47Q1T19UDxlKhMQnjDW4Mmelqu3vzTITnVA7E0ZBgl6jDmlHC8J7ZCX4TW2xB0xoHIySu3MK5d9yUWjqMLdUrRab9KTfH1WyzpEfIbxG7JlhPnZACfiFWFfhvO9vrAZCrAZDZD&until=1483524417&__paging_token=enc_AdBeiIQZBem7NbobO8r183HtpPnZAOY6CRyehrr8uDJZBXkSS5kKS3YpqdmosFZCGZBobXwMnKW4hEsAIEZCjhYCAL2NdAX7ZCZAyWHZB7GhQCS0IQIqEZBwZDZD"
}
},
"OI.Plavipingvin": {
"data": [
{
"message": "Sretnu novu godinu želi vam Uprava odreda. Budite sretni i zadovoljni. I naravno - pripravni za nove avanture! 🎈 🎈 🎈",
"created_time": "2017-01-02T10:07:27+0000",
"id": "379925365427474_1274199672666701"
},
{
"message": "Jutros na Omanovcu. Imamo snijeg! :)",
"created_time": "2016-12-28T07:03:07+0000",
"id": "379925365427474_1269358063150862"
}
],
"paging": {
"previous": "https://graph.facebook.com/v2.8/379925365427474/posts?fields=message,created_time,id&limit=2&format=json&since=1483351647&access_token=EAACEdEose0cBAMlhIYetCMo0m83Jdo3F7rk4NYmm47Q1T19UDxlKhMQnjDW4Mmelqu3vzTITnVA7E0ZBgl6jDmlHC8J7ZCX4TW2xB0xoHIySu3MK5d9yUWjqMLdUrRab9KTfH1WyzpEfIbxG7JlhPnZACfiFWFfhvO9vrAZCrAZDZD&__paging_token=enc_AdDjsccg8E9vHw7XXgXW22NDK0l3MH4mR5XvwXidebNK2Kb8bdewjPiTLGDP8yNw8rpcHYT8VME5YPxLhZC0QZCjdLkHBYJCQZBYdQQWsfmhmC2yQZDZD&__previous=1",
"next": "https://graph.facebook.com/v2.8/379925365427474/posts?fields=message,created_time,id&limit=2&format=json&access_token=EAACEdEose0cBAMlhIYetCMo0m83Jdo3F7rk4NYmm47Q1T19UDxlKhMQnjDW4Mmelqu3vzTITnVA7E0ZBgl6jDmlHC8J7ZCX4TW2xB0xoHIySu3MK5d9yUWjqMLdUrRab9KTfH1WyzpEfIbxG7JlhPnZACfiFWFfhvO9vrAZCrAZDZD&until=1482908587&__paging_token=enc_AdDZCnhwlRCxibv0aGr141JPdbcHcJssKFjhtToaTpfqKbZABvo5g0fhtCgDpwCNoMBopGK4o0CJxXzRyRJKxLCqOh0belZCXBQdTNZCEF5eRuu6agZDZD"
}
}
}
My current FBClass:
Public Class FBData
Public Property data As New List(Of FBFeed)
End Class
Public Class FBFeed
Public Property message As String
Public Property created_time As DateTime
Public Property id As String
End Class
Current GetPosts function, ordering and showing result:
Public Shared Function GetPosts( accessToken As String ) As FBData
Dim APIlink As String = "https://graph.facebook.com/posts?ids=OI.Plavipingvin,217384491624554&limit=5&fields=message,created_time,id&access_token=" & accessToken
Dim client As New WebClient()
client.Encoding = System.Text.Encoding.UTF8
Dim strJson As [String] = client.DownloadString(APIlink)
Dim result As FBData = Newtonsoft.Json.JsonConvert.DeserializeObject(Of FBData)( strJson )
Return result
End Function
Dim array1 As FBData = GetPosts ( accessToken )
For Each Msg As FBFeed In array1.data.OrderByDescending(Function(x) x.created_time)
Response.Write( i & ". " & Msg.created_time & "<br />" )
Next
What FBClass should I use for serialization of this JSON and how to read FBClass list (or array)? I don't need User-ID or data tags.
While my other answer works, it's a bit clumsy if one has a bunch of feeds to deal with, so this should be a more effective answer. I chose not to edit the previous answer because it's valid depending on one's needs.
Given this revised class structure...
Public Class FBFeed
Public Property data As Datum()
Public Property paging As Paging
End Class
Public Class Datum
Public Property message As String
Public Property created_time As DateTime
Public Property id As String
End Class
Public Class Paging
Public Property previous As String
Public Property [next] As String
End Class
...and this revised GetPosts method...
Public Shared Function GetPosts(accessToken As String, ParamArray args() As String) As Dictionary(Of String, FBFeed)
'Dim APIlink As String = "https://graph.facebook.com/posts?ids=OI.Plavipingvin,217384491624554&limit=5&fields=message,created_time,id&access_token=" & accessToken
Dim Ids As String = Join(args, ",")
Dim APITemplate As String = "https://graph.facebook.com/posts?ids={0}&limit=5&fields=message,created_time,id&access_token={1}"
Dim APIlink As String = String.Format(APITemplate, Ids, accessToken)
Using client As New WebClient()
client.Encoding = Text.Encoding.UTF8
Dim strJson As String = client.DownloadString(APIlink)
Return Newtonsoft.Json.JsonConvert.DeserializeObject(Of Dictionary(Of String, FBFeed))(strJson)
End Using
End Function
...the usage in the page request handler becomes...
Dim MyData As New List(Of Datum)
Dim IdList As New List(Of String)
IdList.Add("OI.Plavipingvin")
IdList.Add("217384491624554")
With GetPosts("Access Token Here", IdList.ToArray)
' We have a Dictionary(Of String, FBFeed) we can flatten with SelectMany
' and consolidate the Datum arrays into the MyData List(Of Datum) above
MyData.AddRange(.Values.SelectMany(Function(x) x.data).ToList())
End With
For Each Msg As Datum In MyData.OrderByDescending(Function(x) x.created_time)
Response.Write(Msg.message & ". " & Msg.created_time & "<br />")
Next
The class structure would have to look like this:
Imports Newtonsoft.Json
Public Class FBData
<JsonProperty(PropertyName:="217384491624554")>
Public Property Feed_217384491624554 As FBFeed
<JsonProperty(PropertyName:="OI.Plavipingvin")>
Public Property Feed_OIPlavipingvin As FBFeed
End Class
Public Class FBFeed
Public Property data As Datum()
Public Property paging As Paging
End Class
Public Class Datum
Public Property message As String
Public Property created_time As DateTime
Public Property id As String
End Class
Public Class Paging
Public Property previous As String
Public Property [next] As String
End Class
Update: Usage:
Dim array1 As FBData = GetPosts ( accessToken )
Dim MyData As New List(Of Datum)
MyData.AddRange(array1.Feed_217384491624554.data)
MyData.AddRange(array1.Feed_OIPlavipingvin.data)
For Each Msg As Datum In MyData.OrderByDescending(Function(x) x.created_time)
Response.Write(Msg.message & ". " & Msg.created_time & "<br />")
Next

ArrayList from Class with Reflection

I need to use Reflection for this problem.
Just a simple code needed written in ASP.net and reflection.
Reflection is a must.
Please take a look attached file for more info and example.
I just want to make the code below working. Output does not work as expected! Shows the same result!
Public Class JoinTables
Public Class userz_N_user_roles
Public userz As New userz
Public user_roles As New user_roles
End Class
End Class
Public Class userz
Public Shared id As Nullable(Of Integer) = Nothing
Public user_name As String
Public email_email As String
Public user_pass As String
End Class
Public Class user_roles
Public id As Nullable(Of Integer) = Nothing
Public role_name As String
End Class
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
Dim ArrayList_users As New ArrayList
Dim MyUser1 As New userz
myuser1.email_email = "1#test.com"
myuser1.user_name = "myuser1"
myuser1.user_pass = "mypass1"
ArrayList_users.Add(MyUser1)
Dim ArrayList_roles As New ArrayList
Dim MyUserRoles1 As New user_roles
MyUserRoles1.id = "1"
MyUserRoles1.role_name = "Admin"
ArrayList_roles.Add(MyUserRoles1)
Dim myuser2 As New userz
myuser2.email_email = "2#test.com"
myuser2.user_name = "myuser2"
myuser2.user_pass = "mypass2"
ArrayList_users.Add(myuser2)
Dim MyUserRoles2 As New user_roles
MyUserRoles2.id = "1"
MyUserRoles2.role_name = "Admin"
ArrayList_roles.Add(MyUserRoles2)
'############ REFLECTION PART ###############
Dim MyArrayList As New ArrayList 'for Response
Dim MyJoinTableClass As New JoinTables.userz_N_user_roles
Dim t As Type = MyJoinTableClass.GetType
t.InvokeMember("userz", BindingFlags.SetField, Nothing, MyJoinTableClass, New Object() {MyUser1})
t.InvokeMember("user_roles", BindingFlags.SetField, Nothing, MyJoinTableClass, New Object() {MyUserRoles1})
'MsgBox(MyUser1.user_name)
MyArrayList.Add(MyJoinTableClass)
Dim MyJoinTableClass2 As New JoinTables.userz_N_user_roles
t = MyJoinTableClass2.GetType
t.InvokeMember("userz", BindingFlags.SetField, Nothing, MyJoinTableClass, New Object() {myuser2})
t.InvokeMember("user_roles", BindingFlags.SetField, Nothing, MyJoinTableClass, New Object() {MyUserRoles2})
MyArrayList.Add(MyJoinTableClass)
Dim filledJoinCls1 As New JoinTables.userz_N_user_roles
filledJoinCls1 = MyArrayList(0)
Dim filledJoinCls1_user1 As New userz
filledJoinCls1_user1 = filledJoinCls1.userz
MsgBox(filledJoinCls1_user1.user_name)
Dim filledJoinCls2 As New JoinTables.userz_N_user_roles
filledJoinCls2 = MyArrayList(1)
Dim filledJoinCls2_user2 As New userz
filledJoinCls2_user2 = filledJoinCls2.userz
MsgBox(filledJoinCls1_user1.user_name & " - " & filledJoinCls2_user2.user_name)
End Sub
Output does not work as expected! Shows the same result!
See below,
public class Employee
{
private long emplNbr;
private string name;
public long EmployeeNumber
{
get { return emplNbr; }
set { emplNbr = value; }
}
public string EmployeeName
{
get { return name; }
set { name = value; }
}
}
Creating an Array of Objects
Employee[] StaffMembers = new Employee[2];
Initializing an Array of Objects
StaffMembers[0] = new Employee();
StaffMembers[0].EmployeeNumber = 20204;
StaffMembers[0].EmployeeName = "Harry Fields";
StaffMembers[1] = new Employee();
StaffMembers[1].EmployeeNumber = 92857;
StaffMembers[1].EmployeeName = "Jennifer Almonds";

Convert string to list of custom objects

Say I have an object Fish with properties like
Public Property ID As Integer
Public Property Name As String
Public Property Type As Integer
Public Property Age As Integer
And I have a string that looks like this:
"Fishes[0].ID=1&Fishes[0].Name=Fred&Fishes[0].Type=1&Fishes[0].Age=3&Fishes[1].ID=2&Fishes[1].Name=George&Fishes[1].Type=2&Fishes[1].Age=5&..."
Is there any way of converting/casting/whatever my string into a list of Fish objects? I can't seem to find anything to help. I do have some control over the format of the string if that would make things easier.
Many thanks
What you need to do is to parse the input string to look for Fishes[X].PROPNAME=VALUE pattern. Loop through all matches found in the string and add into or set the existing object in Dictionary. Use X as each object key in the Dictionary.
Create Fish structure:
Structure Fish
Public ID As String
Public Name As String
Public Type As Integer
Public Age As Integer
End Structure
Codes to process the input string:
Dim Fishes As New Dictionary(Of String, Fish)
Dim m As Match = Regex.Match(str, "Fishes\[(?<key>\d+)]\.(?<prop>.+?)=(?<value>[^&]+)", RegexOptions.IgnoreCase)
Do While m.Success
Dim key As String = m.Groups("key").Value.Trim.ToUpper
Dim prop As String = m.Groups("prop").Value.Trim.ToUpper
Dim value As String = m.Groups("value").Value
' if the key not yet exist in the Dictionary, create and add into it.
If Not Fishes.ContainsKey(key) Then
Fishes.Add(key, New Fish)
End If
Dim thisFish As Fish = Fishes(key) ' get the Fish object for this key
' determine the object property to set
Select Case prop
Case "ID" : thisFish.ID = value
Case "NAME" : thisFish.Name = value
Case "TYPE" : thisFish.Type = CInt(value)
Case "AGE" : thisFish.Age = CInt(value)
End Select
Fishes(key) = thisFish ' since the Fish object is declared as Structure,
' update the Dictionary item of key with the modified object.
' If Fish is declared as Class, then this line is useless
m = m.NextMatch()
Loop
Try this ..
Structure Test
Dim ID As String
Dim Name As String
Dim Type As Integer
Dim Age As Integer
End Structure
In your Button click event ..
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim Fishes As New List(Of Test)
Dim Fish As New Test
Fish.ID = "GF"
Fish.Name = "Gold Fish"
Fish.Age = 1
Fish.Type = 1
Fishes.Add(Fish)
MsgBox(Fishes(0).Name)
End Sub
this is vb.net converted
Public Partial Class test
Inherits System.Web.UI.Page
Protected Sub Page_Load(sender As Object, e As EventArgs)
If Not IsPostBack Then
End If
End Sub
Public Sub MYtest()
Dim ls As New List(Of Fish)()
Dim f As New Fish()
f.ID = 1
f.Name = "My name"
f.Type = "My type"
f.Age = 20
ls.Add(f)
End Sub
End Class
Public Class Fish
Public Property ID() As Integer
Get
Return m_ID
End Get
Set
m_ID = Value
End Set
End Property
Private m_ID As Integer
Public Property Name() As String
Get
Return m_Name
End Get
Set
m_Name = Value
End Set
End Property
Private m_Name As String
Public Property Type() As String
Get
Return m_Type
End Get
Set
m_Type = Value
End Set
End Property
Private m_Type As String
Public Property Age() As Integer
Get
Return m_Age
End Get
Set
m_Age = Value
End Set
End Property
Private m_Age As Integer
End Class
In the comments you mentioned that this is via ASP.Net MVC. The ModelBinder will do everything for you.
public ActionResult UpdateFish(IList<Fish> listOfFish)
{
//the ModelBinder will figure out that the user has posted a list of Fish instances.
//do something with listOfFish
return View(listOfFish);
}

sorting list of custom classes using linq

I have a custom class
Class Item
Public item As String
Public Descrip As String
Public price As String
Public Bin As String
Public Total As Decimal
Public Qty As Integer
End Class
now i have another class
Public Class Default3
Inherits System.Web.UI.Page
Dim c As Int16 = 0
Dim Item3 As New Item
Dim Item2 As New List(Of Item)
now i am adding the items in Item2 of type Item
Item3.Item = String.Format(record(0)) ' Field "Item"
Item3.Descrip = String.Format(record(1)) ' Field "Descrip"
Item3.price = String.Format(record(2)) ' Field "Price"
Item3.Bin = String.Format(record(3)) ' Field "Bin"
Item2.Add(Item3)
Now how can i sort elements in Item2 according to Item3.Bin?
Thanks
Use OrderBy
Item2 = Item2.OrderBy(Function(x) x.Bin).ToList()
Or you can you use Sort
Item2.Sort(Function(x, y) x.Bin.CompareTo(y.Bin))

How can i convert the C# code listed below into VB

i am using the Json.net to serialize an object. the specific object is eventInstance.Properties which is the properties of a windows event log.
i am getting a
Newtonsoft.Json.JsonSerializationException: Self referencing loop detected for property
for C# an example is shown here
string json = JsonConvert.SerializeObject(joe, Formatting.Indented, new JsonSerializerSettings
{
ReferenceLoopHandling = ReferenceLoopHandling.Ignore
});
my line of code is below but i am not sure how to make it work in VB or if it is even possible
command.Parameters.AddWithValue("#f18", JsonConvert.SerializeObject(eventInstance.Properties(), New JsonSerializerSettings() {ReferenceLoopHandling = ReferenceLoopHandling.Ignore}))
i get an error that states 'ReferenceLoopHandling' is an enum type and cannot be used as an expression
thanks for the help
You can use below code:
Private Function getJSON(sJSON As String) As String
Dim objNews = New List(Of News)()
Dim news = New News()
news.id = ""
news.title = "blah"
Dim lst = New List(Of Object)()
lst.Add(New With {.video_identifier = "id1"})
lst.Add(New With {.video_identifier = "id2"})
news.video_identifier = lst.ToArray()
objNews.Add(news)
Return Newtonsoft.Json.JsonConvert.SerializeObject(New With {.data = objNews})
End Function
Class News
Public Property title As String
Get
Return _title
End Get
Set
_title = value
End Set
End Property
Private _title As String
Private _sId As String
Public Property id As String
Get
Return _sId
End Get
Set
_sId = value
End Set
End Property
Private _youtube_videos As Object() = New List(Of Object)().ToArray()
Public Property video_identifier As Object()
Get
Return _youtube_videos
End Get
Set
_youtube_videos = value
End Set
End Property
End Class
Public Class YoutubeVideos
Private _video_identifier As String
Public Property video_identifier As String
Get
Return _video_identifier
End Get
Set
_video_identifier = value
End Set
End Property
End Class

Resources