Using class and property names as output in JSON - json

I have this DTO:
public class Post
{
public int Id { get; set; }
public string Message { get; set; }
public DateTime CreatedDate { get; set; }
}
Then i have a route in servicestack that return a list of this DTO.
Method signature looks like this: public IList<Post> GetAllPost()
When getting result from this route my json look like this:
[3]
0: {
Id: 2
Message: "itworks1"
CreatedDate: "/Date(1367264995010+0200)/"
}-
1: {
Id: 3
Message: "itworks2"
CreatedDate: "/Date(1367265002050+0200)/"
}-
2: {
Id: 4
Message: "itworks3"
CreatedDate: "/Date(1367265006767+0200)/"
}
However i would like the JSON output to look like this:
posts
post: {
Id: 2
Message: "itworks1"
CreatedDate: "/Date(1367264995010+0200)/"
}-
post: {
Id: 3
Message: "itworks2"
CreatedDate: "/Date(1367265002050+0200)/"
}-
post: {
Id: 4
Message: "itworks3"
CreatedDate: "/Date(1367265006767+0200)/"
}
Is this possible with the servicestack serializer?

Try wrapping your response in an object:
public class PostListResponse
{
public List<Post> Posts { get; set; }
}
...
public PostListResponse GetAllPosts()
Then your json should look like this:
{
"posts":[
{
"id":4,
"message":"intworks3",
"createdDate":"/Date((1367265006767+0200)/"
},
{
"id":5,
"message":"intworks4",
"createdDate":"/Date((1367265006767+0200)/"
},
...
]
}

Related

Map the backend data to Interface in Angular

I am new in Angular. I have issue in mapping. I called Web API in Angular following is the Json object coming from the backend:
{
"productCategoryDataModel": [
{
"productsCategortyName": "Electronics",
"productsList": [
{
"id": 1,
"productName": "Laptop",
"productDescription": "Laptop Core i7",
"productImageUrl": "fsdgdfgdfgdfgd"
},
{
"id": 5,
"productName": "IPad",
"productDescription": "IPad",
"productImageUrl": "hgfhgfhgf"
}
]
},
{
"productsCategortyName": "Grocery",
"productsList": [
{
"id": 3,
"productName": "Tomato",
"productDescription": "Tomato",
"productImageUrl": "dgdfgdfggdfgdf"
},
{
"id": 4,
"productName": "Onion",
"productDescription": "Onion",
"productImageUrl": "hgfhgfgh"
}
]
}
]
}
Following is the Response model class of Web API:
public class ProductsResponseModel
{
public List<ProductCategoryDataModel> ProductCategoryDataModel { get; set; }
}
public class ProductCategoryDataModel
{
public string? ProductsCategortyName { get; set; }
public List<ProductsList> ProductsList { get; set; }
}
public class ProductsList
{
public int Id { get; set; }
public string? ProductName { get; set; }
public string? ProductDescription { get; set; }
public string? ProductImageUrl { get; set; }
}
I have created the following interface in angular for this json:
export interface IProductsResponse {
ProductCategoryDataModel: ProductCategoryDataModel[];
}
export interface ProductCategoryDataModel
{
ProductsCategortyName: string
productsList: ProductsList[];
}
export interface ProductsList
{
ProductId: number;
ProductName: string;
ProductDescription: string;
ProductImageUrl: string;
}
Following is my Service class that calling the API:
#Injectable({
providedIn: 'root'
})
export class ProductsListService {
apiUrl: string = 'https://localhost:7025/api/ProductsManagement/GetAllProducts';
constructor(private httpClient: HttpClient) { }
getProductsGalleryData(): Observable<IProductsResponse[]> {
return this.httpClient.get<IProductsResponse[]>(this.apiUrl);
}
Following is my component ts file:
#Component({
selector: 'app-products-gallery',
templateUrl: './products-gallery.component.html',
styleUrls: ['./products-gallery.component.css']
})
export class ProductsGalleryComponent implements OnInit {
productsList: IProductsResponse[] | undefined;
constructor(private _galleryProducts: ProductsListService) { }
ngOnInit(): void {
this._galleryProducts.getProductsGalleryData().subscribe(data => {
this.productsList = data;
console.log(data);
});
}
}
The data is displayed in the Console in the form of json but i have issue in the HTML file because when i use the ngFor loop for ProductsList the properties are not coming there and it gives me error so how to map the response into the interface and how to write the html to display this data?
The keys in the data delivered by the WebAPI are camelCase, while the Angular interfaces describe PascalCase properties. Change to camelCase in the interfaces and everything should work fine.
Also, I see your product entity has an id key, while your interface describes a ProductId key. You should change that to be id.
Another approach you can take is on your backend model, you can use JsonPropertyName() [coming from System.Text.Json.Serialization] decorator, to change the name of the keys being serialized and map them to the names you have in your Angular interfaces.
E.g.
[JsonPropertyName("ProductsList")]
public List<ProductModel> Products { get; set; }
Note: Keep in mind that .NET5+ (Asp.Net Core) does not serialize model properties PascalCase if they are named PascalCase, instead the default strategy is to turn them into camelCase keys for serialization. This can be configured.

IsWithinDistance method doesn't work with geojson file for library TopologySuite

I'm trying to get all the points within a distance of 10 meter for example. the Withindistance() doesn't work and it doesn't give me any error so i don't know what is the issue.
Here is my controller :
public IActionResult GetWeather()
{
IList<WeatherViewModel> Tags = new List<WeatherViewModel>();
var geometryFactory = NtsGeometryServices.Instance.CreateGeometryFactory(srid: 4326);
var searchAreaCoordinate = new NetTopologySuite.Geometries.Coordinate(-1.88049067645237,52.486034913778894);
var searchArea = geometryFactory.CreatePoint(searchAreaCoordinate);
Root weather = JsonConvert.DeserializeObject<Root>(System.IO.File.ReadAllText(#"C:\local\weather.json"));
var features = (from c in weather.features select c)
.Select(x=> new {x.id,x.type,x.geometry.coordinates,Coor= new Point(x.geometry.coordinates[0],x.geometry.coordinates[1]){ SRID = 4326 },
})
.Where(x=>x.Coor.IsWithinDistance(searchArea, 10))
.ToList();
;
foreach (var item in features)
{
Tags.Add(new WeatherViewModel()
{
id = item.id,
type = item.type,
Long = item.coordinates[0],
Lat = item.coordinates[1],
test = item.Coor.ToString(),
Distance = item.Coor.Distance(searchArea)
// WKT = item.z
// WKT = new NetTopologySuite.Geometries.Coordinate( item.coordinates[0] , item.coordinates[1])
}
);
}
return View(Tags);
}
}
Note that I'm getting all the records . The Where() doesn't work so if i comment it out ill still get all the results:
Json Class
public class Root
{
public string type { get; set; }
public ParameterDescription parameter_description { get; set; }
public List<double> bbox { get; set; }
public List<Feature> features { get; set; }
}
public class Geometry
{
public string type { get; set; }
public List<double> coordinates { get; set; }
}
public class Feature
{
public string id { get; set; }
public string type { get; set; }
public Properties properties { get; set; }
public Geometry geometry { get; set; }
public Geometry Coor {get;set;}
}
Json sample
{
"type": "FeatureCollection",
"features": [
{
"id": "1",
"type": "Feature",
"properties": {
"t": [
1,
],
"s": [
1,
],
"Time": [
"2021-11-01",
]
},
"geometry": {
"type": "Point",
"coordinates": [
-1.881,
52.486
]
}
},
]
}
Any idea?

Android - JSON parsing without the array name using Retrofit

I have json respose with no arrayname.
Below are the code till now I have done.
JSON Response
[
{
"id": 1,
"user_id": 101,
"name": "abc",
"number": 1234567890
},
{
"id": 2,
"user_id": 102,
"name": "xyzzy",
"number": 8888888888
},
{
"id": 3,
"user_id": 103,
"name":"sdfdsdv",
"number": 2222222222
}
]
Interface Class
public interface ApiInterface {
#GET("user/details”)
Call<List<User_List>> getUser(
#Query(“id”)String id
);
}
User_List Class
public class User_List {
#SerializedName("id")
#Expose
int id;
#SerializedName("user_id")
#Expose
int user_id;
#SerializedName("name")
#Expose
String name;
#SerializedName("number")
#Expose
Int number;
public int getId() {
return id;
}
public int getUser_id() {
return user_id;
}
public int getNumber() {
return number;
}
public String getName() {
return name;
}
}
MainActivity Class
Public void fetch() {
ApiInterface apiInterface = ApiClient.getRetrofit().create(ApiInterface.class);
Call<List<User_List>> user = apiInterface.getUser(id);
user(new Callback<List<user_List>>() {
#Override
public void onResponse(Call<List<user_List>> call, retrofit2.Response<List<user_List>> response) {
try{
if (response.isSuccessful()) {
for (int i = 0; i < user_list(); i++) {
int id = user_list.get(i).getId();
String name = user_list.get(i).getName();
}
}else {
}
}catch (Exception e){
e.printStackTrace();
}
}
#Override
public void onFailure(Call<ArrayList<ProductEnquiry_Contributor>> call, Throwable t) {
}
});
}
I tried to parse it but can't find success,Can anyone suggest me how to parse this type of Response using Retrofit?
It gives me failure in response
Error: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $
you can do this like this
#POST("endpoint)
Call<List<yourPOJO> methodname(#Body BodyPOJO bodyPojo);
or
#POST("endpoint)
Call<Response<List<yourPOJO>> methodname(#Body BodyPOJO bodyPojo);

Spring Boot Json Format

I want to create the Json Format as Shown below by using SpringBoot.
[
{
"name": "foo",
"albums": [
{
"title": "album_one",
"artist": "foo",
"ntracks": 12
},
{
"title": "album_two",
"artist": "foo",
"ntracks": 15
}
]
},
{
"name": "bar",
"albums": [
{
"title": "foo walks into a bar",
"artist": "bar",
"ntracks": 12
},
{
"title": "album_song",
"artist": "bar",
"ntracks": 17
}
]
}]
Please help me and please refer spring boot application which helps to create Json format as similar.
You don't need spring boot for this, you can do it using jackson.
You just need to define bean like:
public class ArtistInfo {
private String name;
private List<Album> albums;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<Album> getAlbums() {
return albums;
}
public void setAlbums(List<Album> albums) {
this.albums = albums;
}
public static class Album {
private String title;
private String artist;
private int ntracks;
public Album(String title, String artist, int ntracks) {
super();
this.title = title;
this.artist = artist;
this.ntracks = ntracks;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getArtist() {
return artist;
}
public void setArtist(String artist) {
this.artist = artist;
}
public int getNtracks() {
return ntracks;
}
public void setNtracks(int ntracks) {
this.ntracks = ntracks;
}
}
}
Now you can use Jackson object mapper to produce JSON:
Initialize List of ArtistInfo
ObjectMapper mapper = new ObjectMapper();
List<ArtistInfo> artistInfos = initData();
String json = mapper.writeValueAsString(artistInfos);
System.out.println(json);
If you using this with Spring REST controller, spring will produce json if you return List of ArtistInfo

Add items to JSON using Json.net

Using json.net, I've created a json string which is a serialized version of my data table, and am able to deserialize it back to a data table. Let's say my serialized text looks like this:
[{ username: "alan", firstName: "Alan", lastName: "Johnson", email: "alan#test.com" },
{ username: "allison", firstName: "Allison", lastName: "House", email: "al#test.com" },
{ username: "ryan", firstName: "Ryan", lastName: "Carson", email: "ryan#test.com" } ]
What I'd like to do is add some text to the beginning before the [, or to the end after the ], which would be included in the json text and not hinder the deserialization back to a data table.
I'm using the serialize command, sometimes with a class object as the second (optional) parameter of the serialization command, sometimes not. If I use the second argument, it results in a much more verbose json, which includes table and column definition information.
Either way, I want to possibly add a segment in the json text which will indicate success or failure of the lookup, but will not cause the deserialization to break.
Can anybody suggest a json.net method to do this?
Thanks...
public class Users
{
public string username { get; set; }
public string firstName { get; set; }
public string lastName { get; set; }
public string email { get; set; }
}
dynamic usercollectionWrapper = new
{
userList = new List<Users>
{
new Users()
{
username= "alan", firstName= "Alan", lastName= "Johnson", email= "alan#test.com"
},
new Users()
{
username= "allison", firstName= "Allison", lastName= "House", email= "al#test.com"
},
new Users()
{
username= "ryan", firstName= "Ryan", lastName= "Carson", email= "ryan#test.com"
}
}
};
var output = JsonConvert.SerializeObject(usercollectionWrapper);
Fiddle:https://dotnetfiddle.net/aAZ3Ah
Update:
public class Users
{
public string username { get; set; }
public string firstName { get; set; }
public string lastName { get; set; }
public string email { get; set; }
}
public class RootUsers
{
public string status { get; set; }
public List<Users> data { get; set; }
}
dynamic usercollectionWrapper = new
{
add = new RootUsers()
{
status = "success",
data = new List<Users>
{
new Users()
{
username= "alan", firstName= "Alan", lastName= "Johnson", email= "alan#test.com"
},
new Users()
{
username= "allison", firstName= "Allison", lastName= "House", email= "al#test.com"
},
new Users()
{
username= "ryan", firstName= "Ryan", lastName= "Carson", email= "ryan#test.com"
}
}
}
};
var output = JsonConvert.SerializeObject(usercollectionWrapper);
Fiddle:https://dotnetfiddle.net/Ic6M1Z