1

I'm using Newtonsoft to deserialize JSON data to an object.

My JSON looks like this:

{
    "id": "4aa50d01-41bd-45e3-803e-f479a948acf1",
    "referenceNumber": "120064",
    "status": "Application in Progress",
    "borrowers": [
    {
        "name": "John Doe",
        "type": "BORROWER"
    },
    {
        "name": "Jane Doe",
        "type": "COBORROWER"
    }
    ],
    "propertyAddress": {
        "zipCodePlusFour": ""
    }
}

The borrowers array can have up to 2 items. 1 with type == "BORROWER"and the other with type == "COBORROWER"

I have a LoanItem class I am deserializing to.

public class LoanItem
{
    public string referenceNumber { get; set; }
    public string status { get; set; }
}

I know I can mark the LoanItem property with the JSONProperty attribute but I'm wondering if there is a way I can add an array sub item with a condition.

Something maybe like

[JSONProperty("borrowers[WHERE type = 'BORROWER'].name")]
public string BorrowerName { get; set; }

[JSONProperty("borrowers[WHERE type = 'COBORROWER'].name")]
public string CoBorrowerName { get; set; }

Is this possible? Can I use the JSONProperty attribute?

3
  • 2
    Nope, that's not how it works. Commented Feb 1, 2017 at 4:15
  • @JeffMercado so I'll just have to manually parse the JSON and map to my objects? Commented Feb 1, 2017 at 4:19
  • You make it sound like it's a bad thing. The JsonPropertyAttribute is not designed to do what you want in that way. It's a way to map a simple json property to a .net property. What you're proposing is far more complex than any of the APIs provide. If you want more complex logic, you'll have to be the one to provide it. Commented Feb 1, 2017 at 18:15

1 Answer 1

2

Create a new class Borrower

public class Borrower 
{
    string Name { get; set; }
    string Type { get; set; }
}

Update your LoanItem class to this

public class LoanItem
{
    public string referenceNumber { get; set; }
    public string status { get; set; }
    public List<Borrower> Borrowers {get;set;}
    public string BorrowerName { get { return Borrowers.Where(x=>x.Type == "BORROWER").FirstOrDefault().Name; }
    public string CoBorrowerName { get { return return Borrowers.Where(x=>x.Type == "COBORROWER").FirstOrDefault().Name; } }
}

Now you can access the BorrowerName and CoborrowerName

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, I was thinking so much about how I could use the JSONProperty attribute that I didn't even consider a simple solution.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.