I am developing windows form application in framework 4.0. I am using JSON.NET. I have the following json in a string variable. I have the 10 classes in the json as follows. How to parse the following json and convert it into List
[
{
"Class": 1,
"ClassUrl": "EngineeringSemister12014A",
"OEPTitle": "Engineer",
"Subject": [
{
"Id": 1,
"OEPTitle": "Algebra"
},
{
"Id": 2,
"OEPTitle": "Maths"
}
],
"IsArchived": true
},
{
"Class": 7,
"ClassUrl": "Engineer2014A",
"OEPTitle": "Engineer",
"Subject": [
{
"Id": 1,
"OEPTitle": "Algebra"
},
{
"Id": 2,
"OEPTitle": "Maths"
}
]
},
{
"Class": 8,
"ClassUrl": "Engineer22014A",
"OEPTitle": "Engineer2",
"Subject": [
{
"Id": 1,
"OEPTitle": "Algebra"
},
{
"Id": 2,
"OEPTitle": "Maths"
}
]
},
{
"Class": 9,
"ClassUrl": "Engineer32014A",
"OEPTitle": "Engineer3",
"Subject": [
{
"Id": 1,
"OEPTitle": "Algebra"
},
{
"Id": 2,
"OEPTitle": "Maths"
}
]
},
{
"Class": 10,
"ClassUrl": "Engineer32014B",
"OEPTitle": "Engineer3",
"Subject": [
{
"Id": 1,
"OEPTitle": "Algebra"
},
{
"Id": 2,
"OEPTitle": "Maths"
},
{
"Id": 8,
"OEPTitle": "english"
}
],
"IsRecycled": true
},
{
"Class": 12,
"ClassUrl": "Engineer52014B",
"OEPTitle": "Engineer5",
"Subject": [
{
"Id": 1,
"OEPTitle": "Algebra"
},
{
"Id": 2,
"OEPTitle": "Maths"
},
{
"Id": 8,
"OEPTitle": "english"
}
]
},
{
"Class": 13,
"ClassUrl": "Engineer62014B",
"OEPTitle": "Engineer6",
"Subject": [
{
"Id": 1,
"OEPTitle": "Algebra"
},
{
"Id": 2,
"OEPTitle": "Maths"
},
{
"Id": 8,
"OEPTitle": "english"
}
]
},
{
"Class": 16,
"ClassUrl": "Mechanical2014undefined",
"OEPTitle": "Mechanical Branch",
"Subject": [
{
"Id": 6,
"OEPTitle": "history"
},
{
"Id": 4,
"OEPTitle": "chemical "
}
]
},
{
"Class": 6,
"ClassUrl": "Engineer12014A",
"OEPTitle": "Engineer1",
"Subject": [
{
"Id": 1,
"OEPTitle": "Algebra"
},
{
"Id": 2,
"OEPTitle": "Maths"
},
{
"Id": 6,
"OEPTitle": "history"
},
{
"Id": 4,
"OEPTitle": "chemical "
}
]
},
{
"Class": 11,
"ClassUrl": "Engineer42014B",
"OEPTitle": "Engineer4",
"Subject": [
{
"Id": 1,
"OEPTitle": "Algebra"
},
{
"Id": 2,
"OEPTitle": "Maths"
},
{
"Id": 6,
"OEPTitle": "history"
},
{
"Id": 4,
"OEPTitle": "chemical "
},
{
"Id": 8,
"OEPTitle": "english"
}
]
}
]
Using json2csharp:
public class Subject
{
public int Id { get; set; }
public string OEPTitle { get; set; }
}
public class RootObject
{
public int Class { get; set; }
public string ClassUrl { get; set; }
public string OEPTitle { get; set; }
public List<Subject> Subject { get; set; }
public bool IsArchived { get; set; }
}
and now, you can use JSON.NET:
List<RootObject> rootObj = JsonConvert.Deserialize<List<RootObject>>(yourJsonHere);
Related
i have a table users which have a column with foreign key... when i post a request in postman of get or get by id it shows the foreign key table data also. i want to show only "USERS" table data only.
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Description;
using Taylor.Models;
namespace Taylor.API_Controller
{
[RoutePrefix("api/Suit")]
public class SuitController : ApiController
{
public TaylorEntities db = new TaylorEntities();
// GET api/<controller>
public List<Suit> GetAllSuit()
{
return db.Suit.ToList();
}
here is a class
namespace Taylor.Models
{
using System;
using System.Collections.Generic;
public partial class Users
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public Users()
{
this.AppUser = new HashSet<AppUser>();
}
public int UserId { get; set; }
public string Name { get; set; }
public string PhoneNumber { get; set; }
public string Email { get; set; }
public int UserRoleId { get; set; }
public bool IsActive { get; set; }
public Nullable<System.DateTime> CreatedAt { get; set; }
public int CreatedBy { get; set; }
public Nullable<System.DateTime> ModifiedAt { get; set; }
public int ModifiedBy { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<AppUser> AppUser { get; set; }
public virtual UserRole UserRole { get; set; }
}
}
in POSTMAN when i request a GET METHOD https://localhost:44311/api/User/6
it shows this much data
{
"$id": "1",
"AppUser": [],
"UserRole": {
"$id": "2",
"Users": [
{
"$ref": "1"
},
{
"$id": "3",
"AppUser": [
{
"$id": "4",
"Location": {
"$id": "5",
"AppUser": [
{
"$ref": "4"
},
{
"$id": "6",
"Location": {
"$ref": "5"
},
"Users": {
"$ref": "3"
},
"Customer": [],
"AppUserId": 4,
"AdminUserId": 1,
"StartDate": "2021-07-26T04:18:42.893",
"EndDate": "2021-07-26T04:18:42.893",
"LocationId": 1,
"City": "Lahore",
"RegisterDate": "2021-07-26T04:18:42.893",
"IsActive": true,
"CreatedAt": "2021-07-26T04:18:42.893",
"CreatedBy": 1,
"ModifiedAt": "2021-07-26T04:18:42.893",
"ModifiedBy": 1
},
{
"$id": "7",
"Location": {
"$ref": "5"
},
"Users": {
"$ref": "3"
},
"Customer": [],
"AppUserId": 5,
"AdminUserId": 1,
"StartDate": "2021-07-26T04:18:42.893",
"EndDate": "2021-07-26T04:18:42.893",
"LocationId": 1,
"City": "Islamabad",
"RegisterDate": "2021-07-26T04:18:42.893",
"IsActive": true,
"CreatedAt": "2021-07-26T04:18:42.893",
"CreatedBy": 1,
"ModifiedAt": "2021-07-26T04:18:42.893",
"ModifiedBy": 1
},
{
"$id": "8",
"Location": {
"$ref": "5"
},
"Users": {
"$id": "9",
"AppUser": [
{
"$ref": "8"
}
],
"UserRole": {
"$ref": "2"
},
"UserId": 3,
"Name": "Haider",
"PhoneNumber": "0347-8526942",
"Email": "haider#yahoo.com",
"UserRoleId": 1,
"IsActive": true,
"CreatedAt": "2021-07-26T04:18:42.893",
"CreatedBy": 1,
"ModifiedAt": "2021-07-26T04:18:42.893",
"ModifiedBy": 1
},
"Customer": [
{
"$id": "10",
"AppUser": {
"$ref": "8"
},
"Nap": [
{
"$id": "11",
"Customer": {
"$ref": "10"
},
"NapDetails": [
{
"$id": "12",
"Nap": {
"$ref": "11"
},
"Suit": {
"$id": "13",
"NapDetails": [
{
"$ref": "12"
}
],
"SuitId": 1,
"Title": "Pent",
"IsActive": true,
"CreatedAt": "2021-07-25T00:00:00",
"CreatedBy": 1,
"ModifiedAt": "2021-07-25T00:00:00",
"ModifiedBy": 1
},
"NapDetailsId": 1,
"SuitId": 1,
"Measurement": "62,25,2514",
"NapId": 1,
"IsActive": true,
"CreatedAt": "2021-07-29T00:00:00",
"CreatedBy": 1,
"ModifiedAt": "2021-07-29T00:00:00",
"ModifiedBy": 1
},
{
"$id": "14",
"Nap": {
"$ref": "11"
},
"Suit": {
"$id": "15",
"NapDetails": [
{
"$ref": "14"
}
],
"SuitId": 2,
"Title": "Shirt",
"IsActive": true,
"CreatedAt": "2021-07-25T00:00:00",
"CreatedBy": 1,
"ModifiedAt": "2021-07-25T00:00:00",
"ModifiedBy": 1
},
"NapDetailsId": 2,
"SuitId": 2,
"Measurement": "fbsh,2514785",
"NapId": 1,
"IsActive": true,
"CreatedAt": "2021-07-26T04:18:42.893",
"CreatedBy": 1,
"ModifiedAt": "2021-07-26T04:18:42.893",
"ModifiedBy": 1
}
],
"NapId": 1,
"CustomerId": 1,
"ImageUrl": "sgjakdvaksgfew",
"IsActive": true,
"CreatedAt": "2021-07-26T04:18:42.893",
"CreatedBy": 1,
"ModifiedAt": "2021-07-26T04:18:42.893",
"ModifiedBy": 1
},
{
"$id": "16",
"Customer": {
"$ref": "10"
},
"NapDetails": [],
"NapId": 4,
"CustomerId": 1,
"ImageUrl": "sgjakdvaksgfew",
"IsActive": true,
"CreatedAt": "2021-07-26T04:18:42.893",
"CreatedBy": 1,
"ModifiedAt": "2021-07-26T04:18:42.893",
"ModifiedBy": 1
}
],
"CustomerId": 1,
"AppUserId": 3,
"PhoneNumber": "0321-8521475",
"CustomerName": "Talha",
"Address": "Multan",
"IsActive": true,
"CreatedAt": "2021-07-26T04:18:42.893",
"CreatedBy": 1,
"ModifiedAt": "2021-07-26T04:18:42.893",
"ModifiedBy": 1
},
{
"$id": "17",
"AppUser": {
"$ref": "8"
},
"Nap": [],
"CustomerId": 3,
"AppUserId": 3,
"PhoneNumber": "0321-8521475",
"CustomerName": "Abu Bakar",
"Address": "Multan",
"IsActive": true,
"CreatedAt": "2021-07-26T04:18:42.893",
"CreatedBy": 1,
"ModifiedAt": "2021-07-26T04:18:42.893",
"ModifiedBy": 1
}
],
"AppUserId": 3,
"AdminUserId": 3,
"StartDate": "2021-07-26T00:00:00",
"EndDate": "2021-07-31T00:00:00",
"LocationId": 1,
"City": "karachi",
"RegisterDate": "2001-12-15T00:00:00",
"IsActive": true,
"CreatedAt": "2021-07-26T00:00:00",
"CreatedBy": 1,
"ModifiedAt": "2021-07-26T00:00:00",
"ModifiedBy": 1
}
],
"Location1": {
"$ref": "5"
},
"Location2": {
"$ref": "5"
},
"LocationId": 1,
"Lat": 0.254,
"Long": 0.568,
"IsActive": true,
"CreatedAt": "2021-07-15T00:00:00",
"CreatedBy": 1,
"ModifiedAt": "2021-07-15T00:00:00",
"ModifiedBy": 1
},
"Users": {
"$ref": "3"
},
"Customer": [],
"AppUserId": 1,
"AdminUserId": 1,
"StartDate": "2021-06-15T00:00:00",
"EndDate": "2021-07-15T00:00:00",
"LocationId": 1,
"City": "multan",
"RegisterDate": "2001-06-24T00:00:00",
"IsActive": true,
"CreatedAt": "2021-07-15T00:00:00",
"CreatedBy": 1,
"ModifiedAt": "2021-07-15T00:00:00",
"ModifiedBy": 1
},
{
"$ref": "6"
},
{
"$ref": "7"
}
],
"UserRole": {
"$ref": "2"
},
"UserId": 1,
"Name": "Khakan",
"PhoneNumber": "0300-1234567",
"Email": "khakan#gmail.com",
"UserRoleId": 1,
"IsActive": true,
"CreatedAt": "2021-07-26T00:00:00",
"CreatedBy": 1,
"ModifiedAt": "2021-07-26T00:00:00",
"ModifiedBy": 1
},
{
"$ref": "9"
},
{
"$id": "18",
"AppUser": [],
"UserRole": {
"$ref": "2"
},
"UserId": 4,
"Name": "Shahzad",
"PhoneNumber": "0347-8526942",
"Email": "shahzad#hotmail.com",
"UserRoleId": 1,
"IsActive": true,
"CreatedAt": "2021-07-26T00:00:00",
"CreatedBy": 1,
"ModifiedAt": "2021-07-26T00:00:00",
"ModifiedBy": 1
},
{
"$id": "19",
"AppUser": [],
"UserRole": {
"$ref": "2"
},
"UserId": 7,
"Name": "Mr. Johny",
"PhoneNumber": "0300-6589321",
"Email": "johny#hotmail.com",
"UserRoleId": 1,
"IsActive": true,
"CreatedAt": "2021-07-26T04:18:42.893",
"CreatedBy": 1,
"ModifiedAt": "2021-07-26T04:18:42.893",
"ModifiedBy": 1
},
{
"$id": "20",
"AppUser": [],
"UserRole": {
"$ref": "2"
},
"UserId": 8,
"Name": "Usman Khan",
"PhoneNumber": "0321-9632584",
"Email": "usman#gmail.com",
"UserRoleId": 1,
"IsActive": true,
"CreatedAt": "2021-07-26T04:18:42.893",
"CreatedBy": 1,
"ModifiedAt": "2021-07-26T04:18:42.893",
"ModifiedBy": 1
}
],
"UserRoleId": 1,
"Title": "Admin",
"IsActive": true,
"CreatedAt": "2021-07-26T00:00:00",
"CreatedBy": 1,
"ModifiedAt": "2021-07-26T00:00:00",
"ModifiedBy": 1
},
"UserId": 6,
"Name": "Awais",
"PhoneNumber": "0321-9632584",
"Email": "awais#hotmail.com",
"UserRoleId": 1,
"IsActive": true,
"CreatedAt": "2021-07-26T04:18:42.893",
"CreatedBy": 1,
"ModifiedAt": "2021-07-26T04:18:42.893",
"ModifiedBy": 1
}
but i want only this one
"UserId": 6,
"Name": "Awais",
"PhoneNumber": "0321-9632584",
"Email": "awais#hotmail.com",
"UserRoleId": 1,
"IsActive": true,
"CreatedAt": "2021-07-26T04:18:42.893",
"CreatedBy": 1,
"ModifiedAt": "2021-07-26T04:18:42.893",
"ModifiedBy": 1
}
You need to give more information on what framework you are using on the backend side to interact with the database.
If entity framework has been used, probably the query to get the result from the database has "Include" extension method, that's why it is fetching the foreign data too.
You can create new User like this for given Id
var user = conetxt.Users
.Select(u=> new User{ UserId = u.UserId, UserName = u.UserName, ... })
.SingleOrDefault(u=>u.UserId == id);
If you want have List<User>
var user = conetxt.Users
.Select(u=> new User{ UserId = u.UserId, UserName = u.UserName, ... })
.ToList();
It is suggested to use
DTO
instead of Model for Response You should expose only required properties to the client
I have a simple JSON reading class that should grab values from a JSON object and put it in c# variables. Right now it uses 8 if statements, but I was wondering if this can be done in a smoother way.
current code:
public Game Read(string filePath)
{
string fileName = "./Levels/TempleOfDoom.json";
JObject json = JObject.Parse(File.ReadAllText(fileName));
Game game = new Game();
foreach (JObject jconnection in json["rooms"])
{
Room room = new Room();
foreach (JProperty jProperty in jconnection.Children().OfType<JProperty>())
{
if (jProperty.Name == "id")
room.id = jProperty.Value.ToObject<int>();
if (jProperty.Name == "width")
room.width = jProperty.Value.ToObject<int>();
if (jProperty.Name == "height")
room.height = jProperty.Value.ToObject<int>();
foreach (JObject jconnection2 in jconnection["items"])
{
Item item = new Item();
foreach (JProperty jProperty2 in jconnection.Children().OfType<JProperty>())
{
if (jProperty.Name == "type")
item.type = jProperty2.Value.ToObject<string>();
if (jProperty.Name == "x")
item.x = jProperty2.Value.ToObject<int>();
if (jProperty.Name == "y")
item.y = jProperty2.Value.ToObject<int>();
if (jProperty.Name == "damage")
item.damage = jProperty2.Value.ToObject<int>();
if (jProperty.Name == "color")
item.color = jProperty2.Value.ToObject<string>();
}
}
}
game.Rooms.Add(room);
}
return game;
}
relevant part of JSON object:
{
"rooms": [
{
"id": 1,
"type": "room",
"width": 5,
"height": 5
},
{
"id": 2,
"type": "room",
"width": 3,
"height": 3
},
{
"id": 3,
"type": "room",
"width": 5,
"height": 5,
"items": [
{
"type": "disappearing boobietrap",
"damage": 1,
"x": 2,
"y": 1
},
{
"type": "sankara stone",
"x": 2,
"y": 2
}
]
},
{
"id": 4,
"type": "room",
"width": 11,
"height": 7,
"items": [
{
"type": "key",
"color": "green",
"x": 1,
"y": 1
},
{
"type": "sankara stone",
"x": 5,
"y": 3
},
{
"type": "boobietrap",
"damage": 1,
"x": 4,
"y": 2
},
{
"type": "boobietrap",
"damage": 1,
"x": 5,
"y": 2
},
{
"type": "boobietrap",
"damage": 1,
"x": 6,
"y": 2
},
{
"type": "boobietrap",
"damage": 1,
"x": 4,
"y": 4
},
{
"type": "boobietrap",
"damage": 1,
"x": 5,
"y": 4
},
{
"type": "boobietrap",
"damage": 1,
"x": 6,
"y": 4
}
]
},
{
"id": 5,
"type": "room",
"width": 5,
"height": 5,
"items": [
{
"type": "key",
"color": "red",
"x": 2,
"y": 3
},
{
"type": "sankara stone",
"x": 2,
"y": 2
}
]
},
{
"id": 6,
"type": "room",
"width": 3,
"height": 3,
"items": [
{
"type": "sankara stone",
"x": 1,
"y": 1
}
]
},
{
"id": 7,
"type": "room",
"width": 5,
"height": 3,
"items": [
{
"type": "pressure plate",
"x": 2,
"y": 1
}
]
},
{
"id": 8,
"type": "room",
"width": 3,
"height": 3
},
{
"id": 9,
"type": "room",
"width": 5,
"height": 5,
"items": [
{
"type": "sankara stone",
"x": 2,
"y": 2
},
{
"type": "boobietrap",
"damage": 1,
"x": 1,
"y": 3
},
{
"type": "boobietrap",
"damage": 1,
"x": 2,
"y": 3
},
{
"type": "boobietrap",
"damage": 1,
"x": 3,
"y": 3
}
]
}
],
}
As you can see, each room has an ID, width and height (type can be ignored) and some rooms have items, which all have a type, x and y coordinate, and some have colors or damage numbers. Is there a better way to get all of these values into a C# class? A game has a List of rooms, and each room can possibly have a list of items.
EDIT: Thanks guys! These lines of code did exactly what I wanted (together with some extra classes for each object game/player/item etc.
public Game Read(string fileName)
{
JObject json = JObject.Parse(File.ReadAllText(fileName));
return JsonConvert.DeserializeObject<Game>(json.ToString());
}
My advice would be to use a webpage called https://json2csharp.com/ that it will create the model class for your json. Sometimes it needs a little tweaking, then is as easy as calling
var json = JsonConverter.DeserializeObject<YourJsonClass>(File.ReadAllText(fileName))
And you would have a class representing your json file, and if you still need to move this information to your custom classes you wouldnt need the if at all just do something like
foreach (var jsonRoom in json.Rooms)
{
room.id = jsonRoom.id;
//and so on
}
You can create a class, for example:
public class Item
{
public string type { get; set; }
public int damage { get; set; }
public int x { get; set; }
public int y { get; set; }
public string color { get; set; }
}
public class Room
{
public int id { get; set; }
public string type { get; set; }
public int width { get; set; }
public int height { get; set; }
public List<Item> items { get; set; }
}
public class MyClass
{
public List<Room> rooms { get; set; }
}
And then deserialize the object as:
MyClass myDeserializedClass = JsonConvert.DeserializeObject<MyClass>(json.ToString());
And then you can access all inside of MyClass and iterate over List<Room> using foreach
This question already has an answer here:
Map category parent id self referencing table structure to EF Core entity
(1 answer)
Closed 2 years ago.
I have an issue on cleaning querying my parent child without repeating the children at its own root of the list.
Object
public class Office
{
public int Id { get; set; }
[Required]
public string Name { get; set; }
public bool Inactive { get; set; }
public int? ParentId { get; set; }
[ForeignKey("ParentId")]
public Office Parent { get; set; }
[InverseProperty("Parent")]
public virtual ICollection<Office> Children { get; set; }
}
}
The Query
public async Task<IEnumerable<Office>> GetOffices()
{
return await _context.Offices.Where(os => !os.Inactive)
.Include(o => o.Parent)
.Include(o => o.Children).ToListAsync();
}
And the result
{
"id": 5,
"name": "AA",
"inactive": false,
"parentId": null,
"parent": null,
"children": []
},
{
"id": 10,
"name": "BAA",
"inactive": false,
"parentId": 2,
"parent": {
"id": 2,
"name": "BA",
"inactive": false,
"parentId": null,
"parent": null,
"children": []
},
"children": [
{
"id": 1011,
"name": "BAAA",
"inactive": false,
"parentId": 10,
"children": []
}
]
},
{
"id": 1011,
"name": "BAAA",
"inactive": false,
"parentId": 10,
"parent": {
"id": 10,
"name": "BAA",
"inactive": false,
"parentId": 2,
"parent": {
"id": 2,
"name": "BA",
"inactive": false,
"parentId": null,
"parent": null,
"children": []
},
"children": []
},
"children": []
},
,
{
"id": 2,
"name": "BA",
"inactive": false,
"parentId": null,
"parent": null,
"children": [
{
"id": 10,
"name": "BAA",
"inactive": false,
"parentId": 2,
"children": [
{
"id": 1011,
"name": "BAAA",
"inactive": false,
"parentId": 10,
"children": []
}
]
}
]
}
This also has child objects at the root level so I tried this
public async Task<IEnumerable<Office>> GetOffices()
{
return await _context.Offices.Where(os => !os.Inactive && !os.ParentId.HasValue).Include(o => o.Parent).Include(o => o.Children).ToListAsync();
}
And this is the result of the other query
{
"id": 5,
"name": "AA",
"inactive": false,
"parentId": null,
"parent": null,
"children": []
},
{
"id": 2,
"name": "BA",
"inactive": false,
"parentId": null,
"parent": null,
"children": [
{
"id": 10,
"name": "BAA",
"inactive": false,
"parentId": 2,
"children": null
}
]
}
This leaves out id 1010 BAAA child object. Idealy I would like to have it come out as
{
"id": 5,
"name": "AA",
"inactive": false,
"parentId": null,
"parent": null,
"children": []
},
{
"id": 2,
"name": "BA",
"inactive": false,
"parentId": null,
"parent": null,
"children": [
{
"id": 10,
"name": "BAA",
"inactive": false,
"parentId": 2,
"children": [
{
"id": 1011,
"name": "BAAA",
"inactive": false,
"parentId": 10,
"children": []
}
]
}
]
}
No matter how I stack the query I can't seem to get this to display this way. Is there a way to adjust the query to allow this or an easy post query command to trim only the root level objects that are a child?
If you want limited number of child levels (2 in this example) fetched you can try:
await _context.Offices
.Where(os => !os.Inactive && !os.ParentId.HasValue)
.Include(o => o.Parent)
.Include(o => o.Children)
.ThenInclude(o => o.Children)
.ToListAsync()
i have following code any one tell me how to convert this in class automatically .its very hard to convert code..please help me
[{
"karhoo_ref": "4325226970648863",
"supplier_company": "supplier1",
"booking_id": "32434234234",
"notes": "waited at southeast corner",
"status": "completed",
"vehicle": {
"vehicle_type": "suv",
"vehicle_id": "404",
"vehicle_plate": "BD51SMR",
"latitude": 40.73892,
"longitude": -73.9873663,
"eta_minutes": null,
"make": "Cadillac",
"model": "Escalade",
"color": "Black",
"eta_minutes": null,
"driver_id": "12121",
"driver_phone": "+14157854978",
"driver_first_name": "Sam",
"driver_last_name": "Smith",
"direction": {
"kph": 20,
"heading": 90
}
},
"total": 29.10,
"currency": "USD"
"price_components": [{
"component_name": "base rate",
"value": 27.10,
"description": "Base Rate"
}, {
"component_name": "parking",
"value": 0,
"description": "Parking"
}, {
"component_name": "tolls",
"value": 0,
"description": "Tolls"
}, {
"component_name": "meet greet",
"value": 0,
"description": "Meet & Greet",
"currency": "USD"
}, {
"component_name": "stop charges",
"value": 0,
"description": "Stop Charges"
}, {
"component_name": "wait time charges",
"value": 0,
"description": "Wait Time charges"
}, {
"component_name": "discount",
"value": 0,
"description": "Discount"
}, {
"component_name": "misc fee",
"value": 0,
"description": "Misc"
}, {
"component_name": "fuel surcharge",
"value": 0,
"description": "Fuel Surcharge"
}, {
"component_name": "service charge",
"value": 0,
"description": "Service Charge"
}, {
"component_name": "gratuity",
"value": 0,
"description": "Tips"
}, {
"component_name": "workers comp tax",
"value": 0,
"description": "NYC Workers Comp Tax"
}, {
"component_name": "tax",
"value": 2.00,
"description": "8.75% State"
}]
}, {
"karhoo_ref": "2825226970648863",
"supplier_company": "supplier2",
"booking_id": "ABC2155",
"notes": "waited at southeast corner",
"status": "completed",
"vehicle": {
"vehicle_type": "sedan",
"vehicle_id": "404",
"vehicle_plate": "BD51SMR",
"latitude": 40.73892,
"longitude": -73.9873663,
"eta_minutes": null,
"make": "Toyota",
"model": "Camery",
"color": "Black",
"driver_id": "12121",
"driver_phone": "4157854978",
"driver_first_name": "Sam",
"driver_last_name": "Smith",
"direction": {
"kph": 20,
"heading": 90
}
},
"total": 27.10,
"currency": "USD"
"price_components": [{
"component_name": "base rate",
"value": 27.10,
"description": "Base Rate"
}]
}]
i want like this.
public class ToLocation
{
public ToLocation()
{
address = new Address2();
}
public double latitude { get; set; }
public double longitude { get; set; }
public Address2 address { get; set; }
public object comment { get; set; }
public object airport { get; set; }
}
I think you should first check whether your string is a valid Json.
You may check below link to convert to class.
How to auto-generate a C# class file from a JSON object string
You're looking for this
Using the dynamic object type. Of course you can do some casting or data mapping later on.
Have a look at JSON.Net. Download the nuget package, than use:
dynamic dyn_json = JsonConvert.DeserializeObject(json);
After that you can iterate through the dynamic object and fill your C# object.
i am getting measurements from withings and want to show them in graphs but not able to convert it to json. i also try JsonConvert.SerializeObject(myString) using Newtonsoft.dlland simple
System.Web.Script.Serialization.JavaScriptSerializer sr = new System.Web.Script.Serialization.JavaScriptSerializer();
sr.Serialize(myString);
but it is not converting.
My withings measurement string is as follows.
{
"status": 0,
"body": {
"updatetime": 1392764547,
"measuregrps": [
{
"grpid": 17945868,
"attrib": 0,
"date": 139984270,
"category": 1,
"measures": [
{
"value": 72,
"type": 9,
"unit": 0
},
{
"value": 152,
"type": 10,
"unit": 7
},
{
"value": 87,
"type": 17,
"unit": 0
}
]
},
{
"grpid": 176587495,
"attrib": 0,
"date": 13915689,
"category": 1,
"measures": [
{
"value": 94,
"type": 9,
"unit": 0
},
{
"value": 145,
"type": 10,
"unit": 0
},
{
"value": 109,
"type": 11,
"unit": 0
}
]
},
{
"grpid": 179262494,
"attrib": 0,
"date": 1391369607,
"category": 1,
"measures": [
{
"value": 77,
"type": 9,
"unit": 0
},
{
"value": 121,
"type": 10,
"unit": 0
},
{
"value": 87,
"type": 11,
"unit": 0
}
]
},
{
"grpid": 179258492,
"attrib": 0,
"date": 1391171167,
"category": 1,
"measures": [
{
"value": 61,
"type": 9,
"unit": 0
},
{
"value": 107,
"type": 10,
"unit": 0
},
{
"value": 80,
"type": 11,
"unit": 0
}
]
},
{
"grpid": 179089150,
"attrib": 0,
"date": 1391167537,
"category": 1,
"measures": [
{
"value": 69,
"type": 9,
"unit": 0
},
{
"value": 112,
"type": 10,
"unit": 0
},
{
"value": 67,
"type": 11,
"unit": 0
}
]
},
{
"grpid": 179079661,
"attrib": 2,
"date": 1391164672,
"category": 1,
"measures": [
{
"value": 720,
"type": 1,
"unit": -1
}
]
},
{
"grpid": 17998560,
"attrib": 2,
"date": 146989672,
"category": 1,
"measures": [
{
"value": 284,
"type": 4,
"unit": -2
}
]
}
]
}
}
It seems, you want to deserialize your json string, not serialize:
var obj = JsonConvert.DeserializeObject<Withings.RootObject>(json);
public class Withings
{
public class Measure
{
public int value { get; set; }
public int type { get; set; }
public int unit { get; set; }
}
public class Measuregrp
{
public int grpid { get; set; }
public int attrib { get; set; }
public int date { get; set; }
public int category { get; set; }
public List<Measure> measures { get; set; }
}
public class Body
{
public int updatetime { get; set; }
public List<Measuregrp> measuregrps { get; set; }
}
public class RootObject
{
public int status { get; set; }
public Body body { get; set; }
}
}
JsonConvert.SerializeObject(myString) takes an object an returns a string. If you want to turn a string into an object you want to use Deserialize<T>(sting json). Given the arguments name in your sample is myString I would assume you're using the method wrong.
To deserialize you need an equivalent type like;
public class myObject
{
public int status { get; set; }
public Body body { get; set; }
}
public class Body
{
//other parameters ect
}
Your object model needs to exactly match the json in order by Deserialize<T> to behave correctly.