1

I want to retrieve data from Json file with webapi using Json file as data source.

In the controller, I have added following code:

Public HttpResponseMessage Get()
{
    var json = File.ReadAllText(System.Web.HttpContext.Current.Server.MapPath(@"~/App_Data\Bim.Json"));

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

and in model,

public class bimModel
{
    public string name { get; set; }
    public string material { get; set; }
    public string tag { get; set; }
    public string contentType { get; set; }
}

Actually, I want to use a json file which is located in app_data folder, how to read data from JSON file? I am very new to the webApi, so it will be of great help if the experts can post the entire working code or as many details as possible, please.

1
  • 1
    your question is not clear, what is your issue? why does your Action not work? why do you have a model where is it used? Commented Mar 20, 2018 at 21:33

1 Answer 1

2

If I am correct, I believe you want to deserialize the json text file to model classes, then serialize them back to json for the client.

To do this, you can use https://www.nuget.org/packages/newtonsoft.json/ to help you out. Follow the instructions to get the package installed.

Once you do that, you can write a function such as

public bimModel Get()
{
    var json = File.ReadAllText(System.Web.HttpContext.Current.Server.MapPath(@"~/App_Data\Bim.Json"));
    var model = JsonConvert.DeserializeObject<bimModel>(json);

    return model;
}

If your json file is an array of bimModels, then you can change the return type and type parameter of DeserializeObject to List<bimModel>.

To ensure your server is returning json to the client, make sure your WebApiConfig class is using the JsonMediaTypeFormatter

public static void Register(HttpConfiguration config)
{
    config.MapHttpAttributeRoutes();
    config.Formatters.Clear();
    config.Formatters.Add(new JsonMediaTypeFormatter());
    config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
    config.Formatters.JsonFormatter.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
    config.Formatters.JsonFormatter.SerializerSettings.Formatting = Formatting.Indented;
}

And of course, be sure to include using Newtonsoft.Json; and using Newtonsoft.Json.Serialization;

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

2 Comments

Thank you @Kevin Le
If this works, would you mind upvoting/marking as answered? Thanks!

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.