I have created WebAPI. In it's GET method I want to load local JSON file and pass it as response. So that when someone accesses this endpoint he will get said JSON response. As I'm total newb with WebAPI and JSON I don't know where to start. Even though I searched a lot through web.
I need something like this (don't know actual functions and classes):
// GET api/values
public JSON Get()
{
var json = File.Load(pathtoJSON.json);
return json;
}
As a newb you can tackle this problem in three steps.
STEP I - Go through some basic tutorial on youtube like these.
STEP II - Create s basic controller (get method) and return a simple String like "Hello World!". Try it and see if you are getting the response.
STEP III - Now you got something working then try to read JSON file and send them as response.
EDIT: if still you got issues, here is some very basic code for you reference:
using Newtonsoft.Json;
using System;
using System.IO;
using System.Web.Http;
public class ValuesController : ApiController
{
public UserData Get()
{
UserData userData = null;
using (StreamReader r = new StreamReader(#"C:\testjson.json"))
{
string json = r.ReadToEnd();
userData = JsonConvert.DeserializeObject<UserData>(json);
}
return userData;
}
public class UserData {
[JsonProperty("first_name")]
public string FirstName;
[JsonProperty("last_name")]
public string LastName;
[JsonProperty("age")]
public String Age;
}
}
and testjson.json
{
"first_name":"FirstTest1",
"last_name":"LastTest1",
"age":"25"
}
and the response
Related
I want to retrieve all the skills form the skills entity in postgresql and send it using get method to the Angular front end.In HTTP request I need to send a JSON object.How can I convert the retrieved values from the postgresql to a JSON object?
I have connected the postgresql db using spring JPA. And also I get a string values to my front end. But I wanted those as JSON object
This is my controller class
#RestController
#CrossOrigin
public class SkillsController {
#Autowired
SkillsRepository skillsRepository;
#RequestMapping("/getSkills")
#GetMapping("/getSkills")
#CrossOrigin
public String getSkills(){
String result = "";
for (Skills skill : skillsRepository.findAll()){
result += skill.toString();
}
return result;
}
This is my Angular front end ts file
public getAllSkills() {
const url = 'http://localhost:8080/getSkills';
this.http.get(url, {responseType: 'text'}).subscribe(
res => {
alert(res);
},
err => {
alert('Error in retrieving');
}
);
}
I want to convert my retrieved valus in to JSON object and catch that object using get method in the front end
Spring uses Jackson serialization/deserialization by default and also the return type is Json. Instead of returning a String return type, return the object itself and it will be converted into Json without any additional code from your end. You controller would typically look as specified below.
#RestController
#CrossOrigin
public class SkillsController {
#Autowired
SkillsRepository skillsRepository;
#GetMapping("/getSkills")
public List<Skill> getSkills() {
return skillsRepository.findAll();
}
}
I will be doing some rewrite to your post. so the answer is pretty straight forward, you can simply return list from the repository and Spring will convert the list to the appriopriate JSON object or array.
#CrossOrigin
public class SkillsController {
public SkillsRepository skillsRepository;
public SkillsController(SkillsRepository _skillsRepository){
skillsRepository = _skillsRepository;
}
#RequestMapping("/getSkills")
#CrossOrigin
public List<skillEntity> getSkills(){
return (List<skillEntity>)skillsRepository.findAll();
}
}
This is with the Docusign Rest api. When I call ToJson() on an EnvelopeDefinition, it returns the correct info, but I would like it to not serialize the base64 array for when I am writing this out to a log file. I tried using the [JsonIgnore] directive, but that stopped the array from being serialized altogether. Do I need to override the Serialize method on this class or just create another method, something like ToJsonForLogging() and not serialize that array?
I have created an extension method that will work for you. You can call this extension method in your code as follows
string json = envelopeDefinition.ToJsonLog(logDocumentBase64:false)
I am copying the DocumentBase64 into a temporary List and then using .ToJson() function to log without the documentBase64 property.
public static class EnvelopeDefinitionExtensions
{
public static string ToJsonLog(this EnvelopeDefinition envDefinition, bool logDocumentBase64 = true)
{
if (logDocumentBase64) return envDefinition.ToJson();
var tempDocumentBase64List = new List<string>();
foreach(var doc in envDefinition.Documents)
{
tempDocumentBase64List.Add(doc.DocumentBase64);
doc.DocumentBase64 = null;
}
string json = envDefinition.ToJson();
int i =0;
foreach(var doc in envDefinition.Documents)
{
doc.DocumentBase64 = tempDocumentBase64List[i];
i++;
}
return json;
}
}
I have a standard Spring 4 MVC application. I have REST endpoints that take the ResponseBody json and maps to my Java objects. This is working great.
But now I have a need to get the raw JSON, as I do not have a Java object to map it to. My endpoint looks like this:
#RequestMapping(value="", method = RequestMethod.POST)
#ResponseBody
public Object createObject(#RequestBody JsonObject objectJson) {
When I POST json to this endpoint I get an empty JSON string. The objectJson is not NULL, but when I debug like this:
System.out.println(objectJson.toString());
I get: {}
when I change the method signature to:
public Object createObject(#RequestBody String objectJson) {
I get a 400 "The request sent by the client was syntactically incorrect"
How do I get the JSON being sent in, either as a String that I can parse manually, or the JsonObject and I can use?
In order to receive a JSON object using #RequestBody, you will need to define a POJO class. Suppose your raw JSON looks like
{"id":"123", "name":"John"}
The POJO will look like
public class User {
private String id;
private String name;
...
// setters and getters
}
Your Controller method will be
#RequestMapping(value="", method = RequestMethod.POST)
#ResponseBody
public Object createObject(#RequestBody User user) {
String id = user.getId();
String name = user.getName();
...
}
I am looking for sending JSON object to the server via GET.
Chris's answer on Post an Array of Objects via JSON to ASP.Net MVC3 works for the http POST but not for GET.
My case also works for POST but not for GET. What can I do to make GET work
Here is my case:
in Controller I have the following method
public ActionResult Screenreport(Screentable screendata)
{
// do something here
return View();
}
I have two ModelView as follows:
public class Screenrecord
{
public string Firstname{ get; set; }
public string Lastname{ get; set; }
}
public class Screentable
{
public List<Screenrecord> Screenlist { get; set; }
}
On the client side I generate JSON object
var Screentable = { Screenlist: screendata };
screendata is an array of Screenrecord
All this work when I use POST but when I use GET I am getting null value (screendata = null) Controllers' method.
In other word when click GO, screendata is null in Screenreport(Screentable screendata) routine.
Also, if I send one JSON object it works but if I send an array (list) like I described, it does not.
Is what I am trying to do doable?
No :-)
Thats not how get works.
http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html
(see 9.3 GET)
"The GET method means retrieve whatever information (in the form of an entity) is identified by the Request-URI"
Request-URI being the important part here. There is no concept of body data in a GET request.
Try changing method to public ActionResult Screenreport(HttpRequestMessage request)
Then use below code to get JSON object.
data = request.RequestUri.Query;
data = HttpUtility.ParseQueryString(data).Get("request");
Try this example in Javascript:
var someObject = {
id:123456,
message:"my message",
}
var objStr = JSON.stringify(someObject);
var escapedObjStr = encodeURIComponent(objStr);
var getUrlStr = "http://myserver:port?json="+escapedObjStr
and now you can forward this URL to your server. I know this is not in any .NET language but you can definitely find the equivalent methods used, or just use the JS right away.
public class JsonCategoriesDisplay
{
public JsonCategoriesDisplay() { }
public int CategoryID { set; get; }
public string CategoryTitle { set; get; }
}
public class ArticleCategoryRepository
{
private DB db = new DB();
public IQueryable<JsonCategoriesDisplay> JsonFindAllCategories()
{
var result = from c in db.ArticleCategories
select new JsonCategoriesDisplay
{
CategoryID = c.CategoryID,
CategoryTitle = c.Title
};
return result;
}
....
}
public class ArticleController : Controller
{
ArticleRepository articleRepository = new ArticleRepository();
ArticleCategoryRepository articleCategoryRepository = new ArticleCategoryRepository();
public string Categories()
{
var jsonCats = articleCategoryRepository.JsonFindAllCategories().ToList();
//return Json(jsonCats, JsonRequestBehavior.AllowGet);
return new JavaScriptSerializer().Serialize(new { jsonCats});
}
}
This results with following:
{"jsonCats":[{"CategoryID":2,"CategoryTitle":"Politika"},{"CategoryID":3,"CategoryTitle":"Informatika"},{"CategoryID":4,"CategoryTitle":"Nova
kategorija"},{"CategoryID":5,"CategoryTitle":"Testna
kategorija"}]}
If I use line that is commented and place JsonResult instead of returning string, I get following result:<
[{"CategoryID":2,"CategoryTitle":"Politika"},{"CategoryID":3,"CategoryTitle":"Informatika"},{"CategoryID":4,"CategoryTitle":"Nova
kategorija"},{"CategoryID":5,"CategoryTitle":"Testna
kategorija"}]
But, I need result to be formatted like this:
{'2':'Politika','3':'Informatika','4':'Nova
kateorija','5':'Testna kategorija'}
Is there a simple way to accomplish this or I will need to hardcode result?
Have a look at the Json.Net library
The Json.NET library makes working
with JavaScript and JSON formatted
data in .NET simple. Quickly read and
write JSON using the JsonReader and
JsonWriter or serialize your .NET
objects with a single method call
using the JsonSerializer.
I have successfully used it within a .net mvc project.
ile,
you really should look at the json.net lib, i was in a similar dilemma recently with json/jquery and mvc and tried my own hand-rolled version but hit the many limitations in my own implemetation. the newton json lib is quite simply a no-brainer - simple to use and always being updated. the current version works fantastically with nested structures, thus making that particular json formatting issue a non-issue.
give it a look, will take you 15 mins to get to grips with.
Try returning it as an Array, Also if you return a JsonResult you can save alot of code (looks like you were attempting to get the formatting you wanted)
public class ArticleController : Controller
{
ArticleRepository articleRepository = new ArticleRepository();
ArticleCategoryRepository articleCategoryRepository = new ArticleCategoryRepository();
public JsonResult Categories()
{
var jsonCats = articleCategoryRepository.JsonFindAllCategories().ToArray();
return Json(jsonCats, JsonRequestBehavior.AllowGet);
}
}
in my test I got a result of
[{"Id":1,"Name":"Cat 1"},{"Id":2,"Name":"Cat 2"}]