Skip to content

Instantly share code, notes, and snippets.

@CarbonHeartDev
Created May 11, 2020 01:09
Show Gist options
  • Save CarbonHeartDev/52a681054839acccc95a1daa1f6dbfbd to your computer and use it in GitHub Desktop.
Save CarbonHeartDev/52a681054839acccc95a1daa1f6dbfbd to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
using System.Text.Json; // Default .NET Core 3 JSON library
using BAMCIS.GeoJSON; // GeoJSON library
namespace Example
{
class Program
{
static void Main(string[] args)
{
string input = "[{\"id\": 2, \"address\": \"whatever\", \"longtitude\": 1.131, \"latitude\": 2.12}, {\"id\": 3, \"address\": \"whatever\", \"longtitude\": 0.321, \"latitude\": -1.321}]";
string output = ApiResponseToGeoJSON(input);
Console.WriteLine(output);
}
public static string ApiResponseToGeoJSON(string apiResponse)
{
// Deserialize JSON response to a POCO (Plain Old C# Object)
ApiPosition[] apiPositions = JsonSerializer.Deserialize<ApiPosition[]>(apiResponse);
// Create a list of Feature (types Feature, Point, Position and FeatureCollection are provided by BAMICS.GeoJSON)
List<Feature> mapFeatures = new List<Feature>();
// For each position from the response create a Feature and add it to previously created list
foreach (ApiPosition apiPosition in apiPositions)
{
mapFeatures.Add(new Feature(
new Point(new Position(apiPosition.latitude, apiPosition.longtitude)),
new Dictionary<string, dynamic>() { { "address", apiPosition.address } }
));
}
// Use the list to build a FeatureCollection
FeatureCollection mapFeatureCollection = new FeatureCollection(mapFeatures);
// FeatureCollection instances provides the method ToJson which converts them to Json strings, use it before sending the FeatureCollection to the frontend
return mapFeatureCollection.ToJson();
}
}
// This type is used to serialize input JSON, it should match input JSON members
public class ApiPosition
{
public int id { get; set; }
public string address { get; set; }
public double longtitude { get; set; }
public double latitude { get; set; }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment