Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
346 views
in Technique[技术] by (71.8m points)

api - Loop through multi-level json coming from FromBody to a model C#

I have a json that I post via postman to my controller in a .net core api, the data arrives in my model Document, which is the following:

public class Document
{
    public int documento_id { get; set; }

    public int document_type { get; set; }

    public string document_company { get; set; }

    public string document_detail { get; set; }

    public List<DocumentLine> lines { get; set; }

}

This first model has several lines of the DocumentLine model, which is the following:

public class DocumetLine
{
    public int document_line_id { get; set; }

    public int document_id { get; set; }

    public int product_category { get; set; }

    public int product_quantity { get; set; }

    public double product_price { get; set; }

}

In my controller I have the following method:

[HttpPost("[action]")]
public IActionResult Receive Document([FromBody] Document model)
{
    var get = new
    {
        document_id = model.document_id,
        document_type = model.document_type,
        document_company = model.document_company,
        document_detail = model.document_detail,

        //Lines of DocumentLine here ... 
     }
}

What I don't know is how to iterate over the lines of the DocumentLine, since the Document has several DocumentLines.

This is my json that I send from postman by post, which corresponds to the Document model and the lines of this which is the DocumentLine model:

{
"document_id": 1,
"document_type": 2,
"document_company": "Some company"
"document_detail": "Send by custumer",
"lines": [{
        "line_number": 1,
        "product_category": 1,
        "product_quantity": 5,
        "product_price": 20.00
    },
    {
        "line_number": 2,
        "product_category": 3,
        "product_quantity": 10,
        "product_price": 40.00
    }
]

}

question from:https://stackoverflow.com/questions/65896501/loop-through-multi-level-json-coming-from-frombody-to-a-model-c-sharp

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Your DocumentLine class does not match the json you sent by postman. line_number is not a property you specified in the class.

The other properties should be accessible like this:

foreach (DocumentLine line in model.lines)
{
    // here you can access the lines like line.product_category.
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...