Sugafree Sugafree - 1 year ago 62
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



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

//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
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
, save it in another
so I can use it for querying matching data from the database of the
web application.

Answer Source

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;


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