Reputation: 1779
I have the following code which is looping through a raw_coords JSON.NET JArray object.
List<string> coords_final = new List<string>();
foreach (var item in raw_coords.Children())
{
var itemcount = item.Count();
for (int i = 0; i < itemcount; i++) //loop through rows
{
var coord_temp1 = item[i].ToString();
coord_temp1 = coord_temp1.Trim(new Char[] { ' ', ',', '.' });
coord_temp1 = coord_temp1.Trim(new Char[] { ' ', '[', '.' });
coord_temp1 = coord_temp1.Trim(new Char[] { ' ', ']', '.' });
coord_temp1 = coord_temp1.Replace(',', ' ');
coords_final.Add(coord_temp1);
}
}
In the above loop, the value of the item
variable is something like:
item [ [ -9221176.0728999991, 4120407.4526000023 ], [ -9221176.0427000001, 4120407.6987999976 ]],[[...],[]]
And, in the data above, the coords_final
does become an array with two elements. But what I need is one string variable which will have data in the form of:
(-9221176.0729 4120407.4526000023, -9221176.0427 4120407.6987999976), (..)..
My code above is adapted from another C# program but the data that currently yields is like:
-9221176.0729 4120407.4526000023, -9221176.0427 4120407.6987999976, -9221176.1341 4120407.4602999985,
which is not what I need.
So how can I make the data to be in the desired format--as shown above? I have tried to prepend "(" and append ")" but that didn't work.
Upvotes: 1
Views: 4277
Reputation: 3306
Assuming raw_coords
is your Jarray
List<string> myCoordsList = new List<string>();
foreach(JToken item in raw_coords)
{
List<string> listOfPairs = new List<string>();
var result = item.ToObject<JArray>();
foreach (JToken jToken in result)
{
var jarray = (JArray) jToken;
IEnumerable<string> nums = jarray.Values<string>();
listOfPairs.Add(string.Join(" ", nums));
}
myCoordsList.Add(string.Format("({0})", string.Join(",", listOfPairs)));
}
string coordsString = string.Join(",", myCoordsList);
the result is
(-9221176.0729 4120407.4526),(-9221176.0427 4120407.6988),(-9221176.1341 4120407.4603),(-9221176.0729 4120407.4526),(-9221176.104 4120407.7063),(-9221176.1341 4120407.4603) ...
for the first few pairs of coords.
Upvotes: 1
Reputation: 33
The following solution gives the result you want:
string json = @"[
[ -9221176.0728999991, 4120407.4526000023 ],
[ -9221176.0427000001, 4120407.6987999976 ]
]";
JArray raw_coords = JArray.Parse(json);
List<string> coords_final = new List<string>();
foreach (var item in raw_coords.Children())
{
coords_final.Add("("+String.Join<object>(",", item)+")");
}
string coords = String.Join(",",coords_final.ToArray());
Console.WriteLine (coords);
(-9221176.0729,4120407.4526),(-9221176.0427,4120407.6988)
Upvotes: 0