Nishant Chandwani
Nishant Chandwani

Reputation: 175

How to set a parameter in json when json is string format

How to set a parameter in json this json is string type, I have using a c# code.

Here is my json;

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

How to set Latitude and Longitude in position 47.64325 and -122.14196

Upvotes: 1

Views: 382

Answers (4)

Steve
Steve

Reputation: 26144

Beginning with C# 11, you can use interpolated raw string literals to make this more terse and pretty removing all of the escaping and string concatenation.

  var latitude = 47.64325;
  var longitude = -122.14196;
  var json = $$"""{"device_id":"nishant","position":"{{latitude}},{{longitude}}"}""";

Upvotes: 0

Alen Lee
Alen Lee

Reputation: 2509

You can use placeholder

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

Upvotes: 0

Mikita Manko
Mikita Manko

Reputation: 1113

With Newtonsoft.Json lib and dynamics you can do something like this:

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);

Here is the working fiddle http://dotnetfiddle.net/Bosonr

Upvotes: 3

Presse
Presse

Reputation: 418

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

Upvotes: 0

Related Questions