Convert Geomtry to Json

1163
5
04-14-2022 04:18 AM
mody_buchbinder
Occasional Contributor III

In arcpy you just do geometry.JSON to get the json string for it.

I could not find a simple way to do the same in ArcObjects.

Convert single geometry (not in feature class) into json (or GeoJson) string.

The GeometryEngine in Pro SDK have ExportToJson.

Anybody?

0 Kudos
5 Replies
GKmieliauskas
Esri Regular Contributor

Hi,

If you use ArcObjects .NET SDK 10.8 you can use JSONConverterGdb class . I don't know if it is available in earlier versions.

Another way is to use .NET serializer:

        public static string To<T>(T obj)
        {
            string retVal = null;
            System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(obj.GetType());
            using (MemoryStream ms = new MemoryStream())
            {
                serializer.WriteObject(ms, obj);
                retVal = Encoding.Default.GetString(ms.ToArray());
            }

            return retVal;
        }

 

 

0 Kudos
mody_buchbinder
Occasional Contributor III

I will give it a try.

I checked the ArcObjects JSONConverterGdb but as far as I understand it gets a Table and not single geometry. I will have to create a temporary table and gets all the attributes and not only geometry.

Thanks

 

0 Kudos
GKmieliauskas
Esri Regular Contributor
0 Kudos
mody_buchbinder
Occasional Contributor III

Here is my final code. The doc's are real bad , no samples and every small change gives catastrophic error with no error message.

 

Have fun

 private string geo2json(IFeature feature)
        {
            IJSONWriter jsonWriter = new JSONWriterClass();
            jsonWriter.WriteToString();
            IJSONSerializer jsonSerializer = new JSONSerializerGdb();
            IPropertySet props = new PropertySetClass();
            props.SetProperty("Format", "GeoJSON");
            jsonSerializer.InitSerializer(jsonWriter, props);
            ((IExternalSerializerGdb)jsonSerializer).WriteGeometry(null, feature.Shape);

            var geoJson = Encoding.UTF8.GetString(jsonWriter.GetStringBuffer());

            return geoJson;
          
        }

 

0 Kudos
FredericWalter
New Contributor III

Another way to do the work is to use JSONConverterGeometry:

 

IJSONConverterGeometry JSONConverterGeometry = new JSONConverterGeometryClass();
IJSONObject JSONGeometry = new JSONObjectClass();
JSONConverterGeometry.QueryJSONGeometry(geometry, true, JSONGeometry);
string strGeometry = JSONGeometry.ToJSONString(null);

 

 

Maybe a litlle bit simplier ...

0 Kudos