Sugafree Sugafree - 5 months ago 23
JSON Question

How to parse a JArray into JObjects, get the first 4 letters of a string of the JObjects and save them back in a JArray

I am using a postcode related API service, where you can get all other postcodes within a given distance of a given postcode.

The following is an example of the

Json
results

{
"postcode":"******",
"lat":111111111,
"lng":11111111,
"distance":0.0
},
{
"postcode":"******",
"lat":2222222222,
"lng":2222222222222,
"distance":0.0343
}


I am using the following in my
API Controller


public object GetPostcodesWithin(string postcode, double distance)
{
var trimPostcode = postcode.Trim();
var url = "some url" + trimPostcode + "&miles=" + distance + "&format=json";
dwml = webClient.DownloadString(url);
dynamic jsonData = JArray.Parse(dwml);
var response = jsonData;

dynamic secondps = jsonData[1];
string newps = secondps.postcode;

JObject rss = JObject.Parse(jsonData);
var postcodes = from p in rss["{ }"]
select (string)p["postcode"];

JArray finalPostcodes = new JArray();
// List<string> finalPostcodes = new List<string>();

foreach (var item in postcodes)
{
var firstletters = item.Substring(0, 4);
finalPostcodes.Add(firstletters);
}
return finalPostcodes;

//int length = response.Count;
//for (int i = 0; i < response.Count; i++)
//{
// var item = (JObject)response[i];

// // JObject o = JObject.Parse(response);
//}

//for (int i=0; i< dwml.Length; i++)
//{
// JToken t[i] = JToken.Parse("{}");

//}

//JObject rss = JObject.Parse(json);

//var postTitles =
//from p in rss["channel"]["item"]
//select(string)p["title"];

//foreach(var item in postTitles)
// {
// Console.WriteLine(item);
// }

// return Json(newps);
}


All the commented out sections are different things I have tried. Basically I get the dynamic
Json
data, but at this line
JObject rss = JObject.Parse(jsonData);
it fails. Goal is to get only the first 4 letters of the postcode attribute of each object in the
JArray
, save it in another
JArray
or
List
so I can use it for querying matching data from the database of the
MVC
web application.

Answer

Try the following:

string yourJsonData = // your json array
var jsonArray = JArray.Parse(yourJsonData);

var resultList = new List<string>();
foreach(var jsonObj in jsonArray)
{
    dynamic obj = jsonObj;
    string postcode = obj.postcode;

    resultList.Add(postcode.Substring(0,4));
}

it will go through all returned items, get the first 4 characters in each postcode and store it in resultList.

Comments