Parse JSON string in JSON LINQ Output

TheCoder 91 Reputation points
2023-02-14T17:18:04.9533333+00:00

I have data in a database column such as:

;kenworth;peterbilt;volvo

I have my LINQ statement such as:

public Task<JsonResult> GetTrucks()
{
     var results = _context.Trucks
      .Select(x => new
       { 
            id = x.Id,
            make = x.Makes,
            model = x.Models
        
       });
      return new JsonResult(results.ToList());
}

My JSON looks like this from the above query:



is there a way to split the makes field and still have them associated with the correct ID? The Makes will be used to populate a dropdown on the UI

Developer technologies .NET Entity Framework Core
Developer technologies C#
{count} votes

2 answers

Sort by: Most helpful
  1. Karen Payne MVP 35,586 Reputation points Volunteer Moderator
    2023-02-15T16:47:48.09+00:00

    If using EF Core 7, consider using json columns, the following provides a simple example, note in code OwnsOne and OwnsMany.

    Getting Started: Entity Framework Core 7 JSON Support

    0 comments No comments

  2. Jack J Jun 25,296 Reputation points
    2023-02-16T03:16:20.0733333+00:00

    @TheCoder, thanks for the feedback, you could refer to Viorel 's advice, to use the string.split() method to get your wanted json string. Since he posted it as a comment and his code has some problems, I will give the correct code example.

     var results = context.Trucks
          .Select(x => new
          {
              id = x.Id,
              make = x.Makes.Split(new string[] {";"}, StringSplitOptions.RemoveEmptyEntries)
    
    
          });
                var result=new JsonResult(results.ToList());
                string json = new JavaScriptSerializer().Serialize(results);
                Console.WriteLine(json);
    
    

    Tested Result:

    User's image

    Hope my advice could help you.

    Best Regards,

    Jack


    If the answer is the right solution, please click "Accept Answer" and upvote it.If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.