Object empty on conversion from json to vb.net classes - asp.net
I have this json that I want to convert to vb.net objects and I've tried to create classes for it without success. The json resonse looks like below:
{
"status": "success",
"result": {
"0": {
"id": 4991,
"sender_id": 2971,
"due_date": "0000-00-00 00:00:00",
"language_id": "sv",
"last_event": "2017-05-17 09:58:38",
"visible_name": "new offer",
"name": "new offer",
"reminder_date": "0000-00-00",
"offer_status": 0,
"offer_type": 1,
"user_details": "{\"first_name\":\"Beta\",\"last_name\":\"\",\"company\":\"Simplesign\",\"email\":\"beta#yopmail.com\",\"reg_no\":\"\",\"address\":\"\",\"telephone\":\"00923453596885\",\"post_code\":\"\",\"city\":\"\"}",
"unique_id": "591c02ae8c442",
"created_date": "2017-05-17 09:58:38",
"signed_date": "0000-00-00 00:00:00",
"last_sent_emailreminder": "0000-00-00 00:00:00",
"last_sent_smsreminder": "0000-00-00 00:00:00",
"unread_notification": 0,
"offer_rejected": 0,
"recieved_by": 0,
"pdf_url": "https://esign.simplesign.io/avtal/downloadpdf/4991/5b8648da173a5",
"details": [
{
"id": 5668,
"offer_sent_id": 4991,
"customer_id": 1556,
"offer_status": 1,
"sent_date": "2017-05-17 09:59:15",
"email_read_date": "0000-00-00 00:00:00",
"document_read_date": "0000-00-00 00:00:00",
"signed_date": "0000-00-00 00:00:00",
"reject_date": "0000-00-00 00:00:00",
"sender_ip": "103.75.244.108",
"read_ip": "",
"signed_ip": "",
"gps_location": "",
"first_name": "John",
"last_name": "Doe",
"company": "",
"is_sender": 0,
"extra_fields": "",
"user_details": "{\"id\":1556,\"full_name\":\"John\",\"email\":\"johndoe#yopmail.com\",\"company\":\"\",\"reg_no\":\"\",\"mobile\":\"\",\"address\":\"\",\"city\":\"\",\"zipcode\":\"\",\"country\":\"\",\"extra_fields\":\"\",\"invitation_order\":1,\"confirmation\":1,\"role\":1,\"id_attachment\":0,\"authentication\":1,\"paypal_amount\":0,\"invitation_type\":1}",
"request_attachment": "[]",
"pin_code": 0,
"invitation_order": 1,
"email": "johndoe#yopmail.com",
"unique_id": "591c02d30379f",
"signature": "",
"signature_type": "",
"signature_font": "",
"authentication_method": 1,
"role": 1,
"id_attachments": 0,
"paypal_amount": 0,
"offer_confirmation": 1,
"invitation_type": 1,
"attached_id": "",
"signature_image": "",
"recieved_by": 0,
"req_attached": "",
"is_pending": 0,
"schedule": "",
"schedule_userid": "",
"isretargeting": 1,
"signature_contrast": "",
"device_details": "",
"evidence_data": "",
"bankid_data": ""
}
],
"senderDetails": [
{
"id": 5667,
"offer_sent_id": 4991,
"customer_id": 0,
"offer_status": 4,
"sent_date": "2017-05-17 09:59:15",
"email_read_date": "0000-00-00 00:00:00",
"document_read_date": "0000-00-00 00:00:00",
"signed_date": "2017-05-17 09:59:15",
"reject_date": "0000-00-00 00:00:00",
"sender_ip": "103.75.244.108",
"read_ip": "",
"signed_ip": "103.75.244.108",
"gps_location": "",
"first_name": "Beta",
"last_name": "",
"company": "Simplesign",
"is_sender": 1,
"extra_fields": "",
"user_details": "{\"id\":2971,\"full_name\":\"Beta\",\"company\":\"Simplesign\",\"address\":\"\",\"country\":\"\",\"zipcode\":\"\",\"city\":\"\",\"reg_no\":\"\",\"email\":\"beta#yopmail.com\"}",
"request_attachment": "",
"pin_code": 0,
"invitation_order": 1,
"email": "beta#yopmail.com",
"unique_id": "591c02d3018d0",
"signature": "",
"signature_type": "",
"signature_font": "",
"authentication_method": 0,
"role": 0,
"id_attachments": 0,
"paypal_amount": 0,
"offer_confirmation": 0,
"invitation_type": 0,
"attached_id": "",
"signature_image": "",
"recieved_by": 0,
"req_attached": "",
"is_pending": 0,
"schedule": "",
"schedule_userid": "",
"isretargeting": 1,
"signature_contrast": "",
"device_details": "",
"evidence_data": "",
"bankid_data": ""
}
]
},
"userSetting": {
"userMsg": "",
"userSMS": "",
"userSubject": ""
},
"pagination": {
"totalRecords": 1,
"pagelimit": 10,
"currentpage": 0
}
},
"totaldata": {
"sent": 1,
"reviewed": 0,
"signed": 0,
"rejected": 0
}
}
The representation looks like this now:
Imports Microsoft.VisualBasic
Imports Newtonsoft.Json
Public Class RecipientDetail
<JsonProperty("id")>
Public Property id As Integer
<JsonProperty("customer_id")>
Public Property customer_id As Integer
<JsonProperty("sent_date")>
Public Property sent_date As String
<JsonProperty("document_read_date")>
Public Property document_read_date As String
<JsonProperty("signed_date")>
Public Property signed_date As String
<JsonProperty("first_name")>
Public Property first_name As String
<JsonProperty("company")>
Public Property company As String
<JsonProperty("is_sender")>
Public Property is_sender As String
<JsonProperty("extra_fields")>
Public Property extra_fields As String
<JsonProperty("user_details")>
Public Property user_details As String
<JsonProperty("invitation_order")>
Public Property invitation_order As Integer
<JsonProperty("email")>
Public Property email As String
<JsonProperty("offer_confirmation")>
Public Property offer_confirmation As String
<JsonProperty("invitation_type")>
Public Property invitation_type As String
End Class
Public Class SenderDetail
<JsonProperty("id")>
Public Property id As Integer
<JsonProperty("customer_id")>
Public Property customer_id As Integer
<JsonProperty("sent_date")>
Public Property sent_date As String
<JsonProperty("signed_date")>
Public Property signed_date As String
<JsonProperty("first_name")>
Public Property first_name As String
<JsonProperty("company")>
Public Property company As String
<JsonProperty("is_sender")>
Public Property is_sender As String
<JsonProperty("extra_fields")>
Public Property extra_fields As String
<JsonProperty("user_details")>
Public Property user_details As String
<JsonProperty("email")>
Public Property email As String
End Class
Public Class ContractDetail
<JsonProperty("sender_id")>
Public Property sender_id As Integer
<JsonProperty("last_event")>
Public Property last_event As String
<JsonProperty("visible_name")>
Public Property visible_name As String
<JsonProperty("offer_status")>
Public Property offer_status As String
<JsonProperty("user_details")>
Public Property user_details As String
<JsonProperty("created_date")>
Public Property created_date As String
<JsonProperty("signed_date")>
Public Property signed_date As String
<JsonProperty("offer_rejected")>
Public Property offer_rejected As String
<JsonProperty("name")>
Public Property name As String
<JsonProperty("contract_id")>
Public Property contract_id As Integer
<JsonProperty("recipientDetails")>
Public Property recipientDetails As IList(Of RecipientDetail)
<JsonProperty("pdf_url")>
Public Property pdf_url As String
<JsonProperty("senderDetails")>
Public Property senderDetails As IList(Of SenderDetail)
End Class
Public Class Pagination
<JsonProperty("totalRecords")>
Public Property totalRecords As Integer
<JsonProperty("pagelimit")>
Public Property pagelimit As Integer
<JsonProperty("currentpage")>
Public Property currentpage As Integer
End Class
Public Class Result
Public Property ContractDetail As IList(Of ContractDetail)
End Class
Public Class SS_History
<JsonProperty("status")>
Public Property status As String
<JsonProperty("result")>
Public Property result As Result
End Class
The problem is that the result is empty, so for some reason it seems that I've done the result class wrong.
If someone have a suggestion of how to solve it I would be most grateful.
Peter
At first, copy the json string.
Open VS, add a new empty class.
Select Edit on VS menu, then Paste Special and Paste Json as Classes. Class will be generated automaticaly.
The first object will be the RootObject, on that one, add Newtonsoft's decorator.
After you added all decorators, you as well can change property names or object names.
Imports Newtonsoft.Json
Public Class Rootobject
<JsonProperty("status")>
Public Property status As String
<JsonProperty("result")>
Public Property result As Result
<JsonProperty("totaldata")>
Public Property totaldata As Totaldata
End Class
etc..
Deserialize it this way:
Json
Related
Is it possible to use response_model data in read_hero function before returning it
I am reading hero with it's foreign key data from database and then return it using response_model. On read_hero function bellow, in this line hero = session.get(Hero, hero_id) hero is different from what this function return when I print it. hero and team schema: class HeroBase(SQLModel): name: str = Field(index=True) secret_name: str age: Optional[int] = Field(default=None, index=True) sponsor: Sponsor = Field(sa_column=Column(JSON(), nullable=False)) team_id: Optional[int] = Field(default=None, foreign_key="team.id") class Hero(HeroBase, table=True): id: Optional[int] = Field(default=None, primary_key=True) team: "Team" = Relationship(back_populates="heroes") class TeamBase(SQLModel): name: str = Field(index=True) headquarters: str class Team(TeamBase, table=True): id: Optional[int] = Field(default=None, primary_key=True) heroes: List["Hero"] = Relationship(back_populates="team") class HeroReadWithTeam(HeroRead): team: "TeamRead" = None #app.get("/heroes/{hero_id}", response_model=HeroReadWithTeam) def read_hero(*,hero_id: int, session: Session = Depends(get_session)): hero = session.get(Hero, hero_id) print(hero) if not hero: raise HTTPException(status_code=404, detail="Hero not found") return hero Line: print(hero) print out secret_name='clement' name='John' team_id=1 age=14 id=2 But the function it self return something like this because of response_model: { "name": "John", "secret_name": "clement", "age": 14, "team_id": 1, "id": 2,, "team": { "name": "Orlando Pirates", "headquarters": "Orlando", "id": 1 } } Is it possible to have this data inside read_hero function and use it before returning it. You can refer from this for full code: https://sqlmodel.tiangolo.com/tutorial/fastapi/relationships/
I think you can do something like: hero_dict = HeroReadWithTeam.from_orm(hero).dict print(hero_dict)
Looping through a list using foreach
I have a project that requires me to populate User information along with their personal information. So far, I was able to loop through a list of users and personal information, but I was not able to populate null values. For example: public List<UserDetailModel> UserInformation() { List<UserDetailModel> userdetails = new List<UserDetailModel>(); var user = _context.User.Where(x => x.Id > 0).ToList() foreach(var item in user) { var personaldetails = _context.PersonalDetails.Where(x => item.PId == x.PId).ToList(); foreach (var item2 in personaldetails) { UserDetailModel userModel = new UserDetailModel(); userModel.UserId = item.UserId; userModel.Name = item.UserName; userModel.PhoneNumber = item.Number; userModel.CreditCardNumber = item2.CCNumber; userModel.SIN = item2.SinNumber; userdetails.Add(userModel); } } return userdetails; } What I'm expecting is: "userId": 1, "name": "john" "phoneNUmber": 123-123-1234, "creditCardNumber": 44455544445554545, "sin": 9589898568 "userId": 1, "name": "john" "phoneNUmber": , "creditCardNumber": 44455544445554545, "sin": 9589898568 "userId": 1, "name": "john" "phoneNUmber": 123-123-1234, "creditCardNumber": , "sin": 9589898568 "userId": 1, "name": "john" "phoneNUmber": 123-123-1234, "creditCardNumber": 44455544445554545, "sin": But what I'm getting with the above code is: "userId": 1, "name": "john" "phoneNUmber": 123-123-1234, "creditCardNumber": 44455544445554545, "sin": 9589898568 How can I get all users along with their null values?
I guess the logic was not implemented correctly, Two loops not required seems, Public List<UserDetailModel> UserInformation(){ List<UserDetailModel> userdetails = new List<UserDetailModel>(); var user = (from user in _context.User join personal in _context.PersonalDetails on user.PId equals personal.PId Where user.Id>0).ToList(); foreach(var item in user) { UserDetailModel userModel = new UserDetailModel(); userModel.UserId = item.UserId; userModel.Name = item.UserName; userModel.PhoneNumber = item.Number; userModel.CreditCardNumber = item2.CCNumber; userModel.SIN = item2.SinNumber; userdetails.Add(userModel); } So when personal details null it won't enter in the loop.
Firebase #Exclude with kotlin data class
I have this data class in Kotlin (example): import com.google.firebase.database.Exclude data class User(val name: String = "", #Exclude val age: Int = 0) And I don't want to save the age property in firebase. #Exclude should do this but it does not work, age is still saved. Are there any workarounds?
Placing #Exclude on a property targets its generated field and not its generated get accesor method. To do the latter you'll need to prefix "Exclude" with "get:". e.g.: data class User(val name: String = "", #get:Exclude val age: Int = 0) See Annotation Use-site Targets for more details.
Actually you don't need to add only #get:Exclude but you need all 3 Exclude, #Exclude #set:Exclude #get:Exclude. I did it for imageUrl and providerId data class FirebaseChatModel( #get:PropertyName("message") #set:PropertyName("message") var message: String = "", #get:PropertyName("type") #set:PropertyName("type") var type: Int = 1, #get:PropertyName("senderId") #set:PropertyName("senderId") var senderId: Int = 0, #get:PropertyName("receiverId") #set:PropertyName("receiverId") var receiverId: Int = 0, #Exclude #set:Exclude #get:Exclude var imageUrl: String? = "", #Exclude #set:Exclude #get:Exclude var providerId: Int = 0 )
Format dateTime from json string
I have some JSON being returned... how can I format these date time strings using c# and JS? { "time": 1469257200, "summary": "Partly cloudy in the morning.", "icon": "partly-cloudy-day", "sunriseTime": 1469279237, "sunsetTime": 1469330841, "moonPhase": 0.63, ...... ..... ... }, and help is appreciated!!!
was easy once I realized that is a unix timestamp: public static DateTime UnixTimeStampToDateTime(double unixTimeStamp) { // Unix timestamp is seconds past epoch System.DateTime dtDateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc); dtDateTime = dtDateTime.AddSeconds(unixTimeStamp).ToLocalTime(); return dtDateTime; }
serialize JSON in ASP.NET with VB
I'm using VB in ASP.NET and I've been looking at trying to serialize the below JSON from a WebService(webmethod). plz help the exact properties that i used. { "api_version" : 4 , "hotel_ids" : [97497], "start_date" : "2013-07-01", "end_date" : "2013-07-03", "num_adults" : 2, "num_rooms" : 1, "currency" : "USD", "user_country" : "US", "device_type" : "d", "query_key" : "6167a22d1f87d2028bf60a8e5e27afa7_191_1360299600000_2_2", "lang" : "en_US", "num_hotels" : 1, "hotels" : [ { "hotel_id": 97497, "room_types": { "Fenway Room": { "url": "http: //www.partner-site.com/hotel_commonwealth/fenway_room?start_date=2013-07-01&end_date=2013-07-05&num_adults=2", "price": 178.50, "fees": 80, "fees_at_checkout": 0, "taxes": 20, "taxes_at_checkout": 0, "final_price": 278.50, "discounts": [ { "marketing_text": "10% off entire stay during July", "is_percent": true, "amount": 10, "price": 20, "fees": 0, "fees_at_checkout": 0, "taxes": 0, "taxes_at_checkout": 0, "final_price": 20 }, { "marketing_text": "1% off web special", "is_percent": true, "amount": 1, "price": 2, "fees": 0, "fees_at_checkout": 0, "taxes": 0, "taxes_at_checkout": 0, "final_price": 2 }, { "marketing_text": "Waive property fee", "is_percent": false, "amount": 25, "price": 0, "fees": 25, "fees_at_checkout": 0, "taxes": 0, "taxes_at_checkout": 0, "final_price": 25 } ], "currency": "USD", "num_rooms": 1, "room_code": "SINGLE", "room_amenities": [ "BREAKFAST_AND_LUNCH_INCLUDED", "ROOM_WITH_A_VIEW" ] } } } ] }
Use Code like this: This is my entity class Public Class Book ' autocomplete example needs "id", "value" and the "label" variables to be sent back. ' do not change or remove "id", "value" and the "label" variables Public Property id() As String Public Property label() As String Public Property value() As String Public Property Author() As String Public Property Genre() As String Public Property Price() As String Public Property Publish_date() As String Public Property Description() As String End Class Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest ' Query string 'term' is for autocomplete. By default, it sends the variable ' "term" with the search word to the backend page. Dim searchText As String = context.Request.QueryString("term") Dim books As Collection = New Collection Dim ds As New DataSet() ds.ReadXml(HttpContext.Current.Server.MapPath("jsonfile")) Dim dv As DataView = ds.Tables(0).DefaultView dv.RowFilter = [String].Format("title like '{0}*'", searchText.Replace("'", "''")) Dim book As Book For Each myDataRow As DataRowView In dv book = New Book() book.id = myDataRow("id").ToString() book.value = myDataRow("title").ToString() book.label = myDataRow("title").ToString() book.Author = myDataRow("author").ToString() book.Genre = myDataRow("genre").ToString() book.Price = myDataRow("price").ToString() book.Publish_date = myDataRow("publish_date").ToString() book.Description = myDataRow("description").ToString() books.Add(book) Next Dim serializer As JavaScriptSerializer = New JavaScriptSerializer Dim jsonString As String = serializer.Serialize(books) context.Response.Write(jsonString) End Sub