0

I have a string called rawJsonPostCodeString that looks like the following JSON.

{
    "status": 200,
    "result": {
        "postcode": "SW1A 1AA",
        "quality": 1,
        "eastings": 529090,
        "northings": 179645,
        "country": "England",
        "nhs_ha": "London",
        "longitude": -0.141588,
        "latitude": 51.501009,
        "european_electoral_region": "London",
        "primary_care_trust": "Westminster",
        "region": "London",
        "lsoa": "Westminster 018C",
        "msoa": "Westminster 018",
        "incode": "1AA",
        "outcode": "SW1A",
        "parliamentary_constituency": "Cities of London and Westminster",
        "admin_district": "Westminster",
        "parish": "Westminster, unparished area",
        "admin_county": null,
        "admin_ward": "St James's",
        "ced": null,
        "ccg": "NHS Central London (Westminster)",
        "nuts": "Westminster",
        "codes": {
            "admin_district": "E09000033",
            "admin_county": "E99999999",
            "admin_ward": "E05000644",
            "parish": "E43000236",
            "parliamentary_constituency": "E14000639",
            "ccg": "E38000031",
            "ced": "E99999999",
            "nuts": "UKI32"
        }
    }
}

I also have a class called PostCodeLocation that looks like the below:

class PostCodeLocation
{        
    public double longitude { get; set; }
    public double latitude { get; set; }
}

I have been using Json.Net to parse this data and then assign it to two items in the class.

Previously I have been using a code like the below to fetch data from a list with multiple results but when I try adapting this to read from my JSON for the post codes it throws an error on the JArray.Parse line for the format being invalid. I have not done any work with JSON before so I am unsure of the best way to process it.

  public List<PostCodeLocation> ProcessJSONPostCodeLocation(string JSonPostCodes)
    {
        JArray PCDetails = JArray.Parse(JSonPostCodes);
        List<JToken> results = PCDetails.Children().ToList();
        List<PostCodeLocaton> PCResults = new List<PostCodeLocation>();
        foreach (JToken result in results)
        {
            PCResults.Add(result.ToObject<PostCodeLocation>());
        }
        return PCResults;
    }

If anyone has any tips it would be greatly appreciated.

K Emery
  • 91
  • 2
  • 12
  • *"just throws an error with parsing or assigning it to a list"* - Can you show the exceptions that it throws? – Gabriel Luci Nov 26 '19 at 14:18
  • 3
    For starters, your json is not valid. And, your model does not match the json. I'll post an answer here in a second. – Casey Crookston Nov 26 '19 at 14:19
  • 1
    Well, the JSON you've posted would not be parseable as an array; it has no square brackets... – Heretic Monkey Nov 26 '19 at 14:21
  • 5
    Possible duplicate of [What is a NullReferenceException, and how do I fix it?](https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) and or this is a debugging issue. – Trevor Nov 26 '19 at 14:21
  • 2
    The typo are : Missing `:` after "result". Missing `,` 3 times after Postcode, long, and lat property. – Drag and Drop Nov 26 '19 at 14:25
  • 2
    If the JSON string was valid, and if you used objects that actually match the JSON string, you could just write `JsonConvert.DeserializeObject()` and read the `Result` property. You gain nothing by parsing the entire string (which isn't an array anyway) and then trying to reconstruct the result object. – Panagiotis Kanavos Nov 26 '19 at 14:28
  • You may want to check https://www.json.org/ official documentation on Json. It's not complexe and has nice drawing on what an array an an object representation is. – Drag and Drop Nov 26 '19 at 14:32
  • @K Emery This may be [helpful](https://stackoverflow.com/a/14977915/1797425) as well. You can validate your `json` before doing anything with it. You never know when the incoming `json` is badly formatted and or not even valid. – Trevor Nov 26 '19 at 15:01

1 Answers1

3

First, your json is not valid. You have this:

{
    "status": 200,
    "result" {
        "postcode": "SW1A 1AA"
        "longitude":-0.141588
        "latitude":51.501009
    }
}

To make it valid json, it needs to look like this:

{
    "status": 200,
    "result": {
        "postcode": "SW1A 1AA",
        "longitude":-0.141588,
        "latitude":51.501009
    }
}

(and that's assuming that result is not an array. If it IS an array, you will need [].)

There is a handy online tool I use all the time to make sure my json strings are valid: https://jsonformatter.curiousconcept.com/

Now that we have valid json to work with, we need a model to match it. Here's another handy online tool that converts your json string into c# objects: http://json2csharp.com/

Using that tool, we get this:

    public class RootObject
    {
        public int Status { get; set; }
        public Result Result { get; set; }
    }

    public class Result
    {
        public string Postcode { get; set; }
        public double Longitude { get; set; }
        public double Latitude { get; set; }
    }

And now, creating an instance of RootObject is as simple as:

RootObject rootObject = Newtonsoft.Json.JsonConvert.DeserializeObject<RootObject>(rawJsonPostCodeString );
Casey Crookston
  • 13,016
  • 24
  • 107
  • 193
  • Downvoter: By the time the answer was written, there still were several typos in the JSON string in the question. The question has been edited to correct this, since. (If that's what the "problem" seemed to be.) – Fildor Nov 26 '19 at 14:32
  • This worked perfectly thanks! I'm new to Json and didnt realize I had input it into this question with some errors. I am fetching this Json from an API which was correct. It appears the issue was with how I am trying to get the data from it. – K Emery Nov 26 '19 at 14:34
  • `I am fetching this Json from an API which was correct` then where's the correct `json`? Even the updated version still is wrong. Also if your getting this from an api and it's supposed to be an array, its wrong. – Trevor Nov 26 '19 at 14:35
  • Rename a property get a new valid question. I didn't vote. But I will be surprise if I see a Json c# question that is not a dupe of either "Use Json2sharp" " use visual studio special past" or "use dictionary string string" by the end of the week. And the famous Array or single item converter – Drag and Drop Nov 26 '19 at 14:36
  • @DragandDrop I see more everyday about this... and it seems answers are similar in a way, check your json here and then go here to create your classes for you... – Trevor Nov 26 '19 at 14:36
  • @KEmery, glad to help! You really ought to spend some time learning about `Newtonsoft`. It will become one of your very favorite tools in your C# toolbox. (Also, please mark this answer as correct, thanks!) – Casey Crookston Nov 26 '19 at 14:38
  • @DragandDrop, yes. You are correct. I guess I like to err on the side of teaching and of being helpful, which is that SO is supposed to be for. – Casey Crookston Nov 26 '19 at 14:40
  • @Casey, No correlation between the vast dupe-yard that Json tag is and teaching. Teacher have many student and give a course to all of them at the same time. Teacher don't get one-one H24 with similar question with different typo. Imagine a clear community question with clear community answers. That's where we should put effort in. – Drag and Drop Nov 26 '19 at 14:42
  • 1
    I read your last comment as "I answer because there is no easly found dupe target that is clear enough, to be serve as an answer". Closing a question as dupe is not bad nor snarky nor rude or anything. Dupe, good dupe is helping. – Drag and Drop Nov 26 '19 at 15:08