当json为字符串格式时如何设置json中的参数

问题描述 投票:0回答:4

如何在json中设置参数这个json是字符串类型,我使用的是c#代码。

这是我的json;

double Latitude = e.current.Latitude;
double Longitude = e.current.Longitude;
string json = "{ \"device_id\" : \"nishant\",\"position\" : \"47.64325,-122.14196\" }";

如何设置位置47.64325和-122.14196的纬度和经度

c# asp.net .net json windows-phone-8
4个回答
3
投票

使用

Newtonsoft.Json
lib 和dynamics,你可以做这样的事情:

double Latitude = 11.1234;
double Longitude = 22.4321;
string json = "{ \"device_id\" : \"nishant\",\"position\" : \"47.64325,-122.14196\" }";

dynamic jsonObject = JsonConvert.DeserializeObject(json);
jsonObject.position = Latitude.ToString() + ',' + Longitude.ToString();
json = JsonConvert.SerializeObject(jsonObject);

这是工作小提琴http://dotnetfiddle.net/Bosonr


0
投票

您可以使用占位符

double Latitude = 47.64325;
double Longitude = -122.14196;
string json = "{" + "\"" + "device_id" + "\"" + ":" + "\"" + "nishant" + "\"" + "," + "\"" + "position" + "\"" + ":" + " \"" + Latitude
                + "," + Longitude + "\"" + " }";

0
投票
double Latitude = e.current.Latitude;
double Longitude = e.current.Longitude;
string json = "{ 'device_id' : 'nishant','position' : '" + Latitude + "','" + Longitude + "'}";

0
投票

从 C# 11 开始,您可以使用 插值原始字符串文字 使之更加简洁,并且可以很好地删除所有转义和字符串连接。

  var latitude = 47.64325;
  var longitude = -122.14196;
  var json = $$"""{"device_id":"nishant","position":"{{latitude}},{{longitude}}"}""";
© www.soinside.com 2019 - 2024. All rights reserved.