Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use an external Json File to serve as a data source for webapi

Following is my code snippet which works fine, my query follows the code:

Model:

namespace CVHub.Models
{
    [DataContract]
    public class Context
    {
        [DataMember]
        public int sessionID { get; set; }
        [DataMember]
        public string Name { get; set; }

        public static List <Context> Contexts= new List<Context>
        {

            new Context{sessionID=1,Name="Name1"},
            new Context {sessionID=2,Name="Name2"},
            new Context {sessionID=3,Name="Name3"}
        };
    }
}

Controller:

namespace CVHub.Controllers
{
    public class ContextController : ApiController
    {
        List<Context> items;
        // GET api/values
        public IEnumerable<Context> Get()
        {
            //return Context.Contexts;
            return items;
        }
    }
}

Question: I want to use an external json file (residing in app_data folder) to serve same data instead of doing new Context{sessionID=1,Name="Name1"}, how to use a data I read from json file? I am very new to MVC and webApi, so it will be of great help if the experts can post the entire working code or as much details as possible please.

like image 240
onlynitins Avatar asked Jul 12 '15 17:07

onlynitins


People also ask

Is JSON a data source?

The JSON data source parses the input JSON expression by using JSONPath and populates the specified properties with the parsed values. In this topic, we focus on how to configure the JSON data source. We assume you are already familiar with data-driven testing and how to configure a data-driven loop.


1 Answers

You can return a HttpResponseMessage with your JSON file loaded into StringContent.

public class JsonFileController : ApiController
{
    public HttpResponseMessage Get()
    {
        var json = File.ReadAllText(Server.MapPath(@"~/App_Data/contexts.json");

        return new HttpResponseMessage()
        {
            Content = new StringContent(json, Encoding.UTF8, "application/json"),
            StatusCode = HttpStatusCode.OK
        };
    }
}

App_Data/contexts.json

[
    {
        "sessionId": 1,
        "name": "name1"
    },
    {
        "sessionId": 2,
        "name": "name2"
    },
    {
        "sessionId": 3,
        "name": "name3"
    }
]
like image 168
Martin Avatar answered Sep 22 '22 14:09

Martin