【问题标题】:Include JSON stream in GeoJson object?在 GeoJson 对象中包含 JSON 流?
【发布时间】:2020-02-15 19:40:03
【问题描述】:

我正在学习如何创建GeoJson 流。我知道如何将datatable 转换为 JSON 字符串,然后序列化为 JSON 格式。问题是我不知道如何将此 JSON 流包含在 GeoJson 对象中。

以下代码生成一个geojson对象:

    public geoJson Leaflets_GeoJson()
    {

        var CorOrd = new LocalGeometry();
        CorOrd.coordinates = new List<double>(); // <=====
        CorOrd.coordinates.Add(34.2305);
        CorOrd.coordinates.Add(-86.2644);
        CorOrd.type = "Point";

        var myProps = new Properties();
        myProps.name = "John";
        myProps.id = "JN123";
        myProps.address = "Howard Street";


        var geoJson = new geoJson
        {
            type = "FeatureCollection",
            features = new List<LocalFeature>
            {
               new LocalFeature { type = "Feature", geometry = CorOrd, properties=myProps}
            }

        };

        return geoJson;

    }

返回以下内容:

{"features":[{"geometry":{"coordinates":[18.2305,-66.2644],"type":"Point"},"properties":{"address":"Howard Street","id":"JN123","name":"John"},"type":"Feature"}],"type":"FeatureCollection"}

这是采用数据表并返回 JSON 流的方法:

public System.IO.Stream()
{
    string sqlQuery = string.Format("usp_GetNames");

    string connString = System.Configuration.ConfigurationManager.ConnectionStrings["connstring"].ToString();
    SqlDatabase sqlDatabase = new SqlDatabase(connString);
    DataSet result = sqlDatabase.ExecuteDataSet(CommandType.Text, sqlQuery);


    string callback = JsonConvert.SerializeObject(result.Tables[0]);
    byte[] resultBytes = Encoding.UTF8.GetBytes(callback);
    return new System.IO.MemoryStream(resultBytes);
}

并返回此JSON:

[
 {"name":"Joe","address":"Main Street","id":"Joe121", "Lon": 40.730610, "Lat": -73.935242}, 
 {"name":"Mary","address":"220 Avenue","id":"Mary625", "Lon": 42.730610, "Lat": -72.935242}
]

我的问题:如何将这两个流结合起来,使其返回一个看起来像这样的 GeoJson 对象?

{ "type": "FeatureCollection", "features": [ {"type": "Feature", "properties": 
   {"name":"Joe","address":"Main Street","id":"Joe121"},"geometry": {"type": "Point","coordinates": [-73.1232, 40.7306]}}, 
   {"type": "Feature", "properties": {"name":"Mary","address":"220 Avenue","id":"Mary625"},"geometry": {"type": "Point","coordinates": [-71.1232, 41.7306]}}] } 

【问题讨论】:

标签: c# json wcf json.net geojson


【解决方案1】:

您需要将该数组包装在实现两个属性(类型和特性)的外部类中。您可以为此使用 C# 匿名类型:

var envelope = new
{
    type = "FeatureCollection",
    features = result.Tables[0]
};

string callback = JsonConvert.SerializeObject(envelope);
byte[] resultBytes = Encoding.UTF8.GetBytes(callback);
//...

【讨论】:

  • 谢谢。我试过了。问题是每个都有额外的静态数据。所以在features 中有另一个json 块。坐标也在一个单独的块中:"features": [ {"type": "Feature", "properties": {"name":"Joe","address":"Main Street","id":"Joe121"},"geometry": {"type": "Point","coordinates": [-73.1232, 40.7306]}}
猜你喜欢
  • 2018-03-21
  • 2012-09-04
  • 2012-04-20
  • 1970-01-01
  • 1970-01-01
  • 2014-12-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多