Click here to Skip to main content
15,887,683 members
Articles / Web Development / ASP.NET
Tip/Trick

GeoJSon to C# Object using Json.NET

,
Rate me:
Please Sign up or sign in to vote.
4.00/5 (7 votes)
28 Oct 2014CPOL1 min read 63.5K   641   7   21
Convert Coordinate data to strings to be stored in database.

Introduction

Convert GeoJson data with multiple coordinates to dynamic C# object to store it in external sources (this case SQL Server) or use in other application logic.

Background

Recently, we were assigned to handle Coordinates data and move it to some external source like Datbase or file to restore it when required according to location. First we tried to serialize GeoJson file and creating object for doing so. But multiple coordinate data was not allowing to do so becuase of nested Json arrays. Which threw exceptions while we replaced nested array to capture insire jagged, nested arrays etc but no use.

So finally we created dynamic object this way which resolved all of over issues. You can use pattern or whole code to resolve your similar issues.

Using the code

First of all add Json.NET package in your project through Nuget: https://www.nuget.org/packages/Newtonsoft.Json/

- Provide connection string of SQL Server in Web.config
- Provide path to geo.json file in web.config

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;

namespace GeoLocations
{
    public class Program
    {
        public static string ConnectionString
        {
            get
            {
                return  System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionSTR"].ConnectionString;
            }
        }
        public static string JsonFilePath
        {
            get
            {
                return System.Configuration.ConfigurationSettings.AppSettings["JsonFilePath"].ToString();
            }
        }

        static void Main(string[] args)
        {
            System.IO.StreamReader file = new System.IO.StreamReader(JsonFilePath);
            string content = file.ReadToEnd();
            file.Close();

            dynamic deserialized = JsonConvert.DeserializeObject(content);
            List<GeoLocation> lstGeoLocation = new List<GeoLocation>();
            foreach (var item in deserialized.features)
            {
                lstGeoLocation.Add(new GeoLocation()
                {
                    GEO_ID = item.properties.GEO_ID,
                    LSAD = item.properties.LSAD,
                    NAME = item.properties.NAME,
                    STATE = item.properties.STATE,
                    COUNTY = item.properties.COUNTY,
                    CENSUSAREA = item.properties.CENSUSAREA,
                    coordinates = item.geometry.coordinates.ToString()
                });
            }

            InsertInDataBase(lstGeoLocation);
        }

        public static void InsertInDataBase(List<GeoLocation> lstGeoLocation)
        {
            SqlConnection connection = new SqlConnection(ConnectionString);

            string createTableString = @"if not exists (select * from sysobjects where name='GeoLocations' and xtype='U')
                                                CREATE TABLE [dbo].[GeoLocations](    [GEO_ID] [varchar](100) NULL,    [STATE] [varchar](100) NULL,    [COUNTY] [varchar](100) NULL,    [NAME] [varchar](100) NULL,    [LSAD] [varchar](100) NULL,    [CENSUSAREA] [varchar](100) NULL,    [coordinates] [varchar](max) NULL) ON [PRIMARY]";

            try
            {
                connection.Open();

                SqlCommand createTable = new SqlCommand(createTableString, connection);

                try { createTable.ExecuteNonQuery(); }
                catch (Exception ex) { }
                finally { createTable.Dispose(); }

                foreach (var item in lstGeoLocation)
                {
                    string insertRecordsString = @"INSERT INTO [dbo].[GeoLocations]
                                            ([GEO_ID], [STATE], [COUNTY], [NAME], [LSAD], [CENSUSAREA], [coordinates])
                                
                                            VALUES(@GEO_ID, @STATE, @COUNTY, @NAME, @LSAD, @CENSUSAREA, '" + item.coordinates + "')";

                    SqlCommand insertCommand = new SqlCommand(insertRecordsString, connection);

                    insertCommand.Parameters.Add("@GEO_ID ", SqlDbType.NVarChar).Value = item.GEO_ID;
                    insertCommand.Parameters.Add("@STATE      ", SqlDbType.NVarChar).Value = item.STATE;
                    insertCommand.Parameters.Add("@COUNTY     ", SqlDbType.NVarChar).Value = item.COUNTY;
                    insertCommand.Parameters.Add("@NAME       ", SqlDbType.NVarChar).Value = item.NAME;
                    insertCommand.Parameters.Add("@LSAD       ", SqlDbType.NVarChar).Value = item.LSAD;
                    insertCommand.Parameters.Add("@CENSUSAREA ", SqlDbType.NVarChar).Value = item.CENSUSAREA;

                    try { insertCommand.ExecuteNonQuery(); }
                    catch (Exception ex) { }
                    finally { insertCommand.Dispose(); }
                }
            }
            catch (Exception) { }
            finally
            {
                connection.Close();
                connection.Dispose();
            }
        }
    }

    public class GeoLocation
    {
        public string GEO_ID { get; set; }
        public string STATE { get; set; }
        public string COUNTY { get; set; }
        public string NAME { get; set; }
        public string LSAD { get; set; }
        public string CENSUSAREA { get; set; }

        public string coordinates { get; set; }
    }
}

Points of Interest

  • Use of Json.NET to write one line code to deserialize json text to object
  • Dynamic object to capture object to reuse for application logic
  • Quick function to insert data into database

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
CEO Relliks Systems
Pakistan Pakistan
https://relliks.com

Written By
Pakistan Pakistan
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
Questiongeojson Pin
Member 1343118316-May-18 20:16
Member 1343118316-May-18 20:16 
AnswerRe: geojson Pin
Muhammad N@beel19-Feb-19 6:17
professionalMuhammad N@beel19-Feb-19 6:17 
QuestionJsonreader exception Pin
ngash27-Aug-15 0:13
ngash27-Aug-15 0:13 
AnswerRe: Jsonreader exception Pin
Muhammad N@beel27-Aug-15 7:47
professionalMuhammad N@beel27-Aug-15 7:47 
GeneralRe: Jsonreader exception Pin
ngash27-Aug-15 22:28
ngash27-Aug-15 22:28 
GeneralRe: Jsonreader exception Pin
Muhammad N@beel28-Aug-15 10:04
professionalMuhammad N@beel28-Aug-15 10:04 
GeneralMy Vote 5 Pin
Shemeemsha (ഷെമീംഷ)28-Oct-14 23:47
Shemeemsha (ഷെമീംഷ)28-Oct-14 23:47 
GeneralMessage Closed Pin
28-Oct-14 23:55
professionalMuhammad N@beel28-Oct-14 23:55 
GeneralRe: My Vote 5 Pin
Shemeemsha (ഷെമീംഷ)28-Oct-14 23:58
Shemeemsha (ഷെമീംഷ)28-Oct-14 23:58 
GeneralRe: My Vote 5 Pin
Muhammad N@beel29-Oct-14 0:00
professionalMuhammad N@beel29-Oct-14 0:00 
GeneralRe: My Vote 5 Pin
Shemeemsha (ഷെമീംഷ)29-Oct-14 0:03
Shemeemsha (ഷെമീംഷ)29-Oct-14 0:03 
You're welcome.. Your tip is very nice Java | [Coffee]
GeneralRe: My Vote 5 Pin
Muhammad N@beel29-Oct-14 0:16
professionalMuhammad N@beel29-Oct-14 0:16 
GeneralRe: My Vote 5 Pin
Shemeemsha (ഷെമീംഷ)29-Oct-14 0:20
Shemeemsha (ഷെമീംഷ)29-Oct-14 0:20 
GeneralRe: My Vote 5 Pin
Muhammad N@beel29-Oct-14 0:26
professionalMuhammad N@beel29-Oct-14 0:26 
GeneralRe: My Vote 5 Pin
Shemeemsha (ഷെമീംഷ)29-Oct-14 0:27
Shemeemsha (ഷെമീംഷ)29-Oct-14 0:27 
QuestionData import Pin
JacobLux28-Oct-14 11:21
JacobLux28-Oct-14 11:21 
AnswerRe: Data import Pin
Muhammad N@beel28-Oct-14 21:15
professionalMuhammad N@beel28-Oct-14 21:15 
GeneralRe: Data import Pin
JacobLux29-Oct-14 10:51
JacobLux29-Oct-14 10:51 
GeneralRe: Data import Pin
Muhammad N@beel29-Oct-14 22:02
professionalMuhammad N@beel29-Oct-14 22:02 
GeneralRe: Data import Pin
JacobLux30-Oct-14 1:11
JacobLux30-Oct-14 1:11 
GeneralRe: Data import Pin
Muhammad N@beel30-Oct-14 1:20
professionalMuhammad N@beel30-Oct-14 1:20 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.