Json dynamic string list - json

I want to return a list of validation errors from my mvc app to the client side to I can take use of the jquery validation showErrors which takes an object
I can get a list of fields and the the erorr(s) that apply to them in any way that is best suited.
I have tried a few formats already, dictionary and none of these serialise to the correct structure as required by the validation library.
ie.
{"fieldname":"some error for fieldname", "fieldname2": "some error for fieldname2"}
All of my examples seem to serialise into something along the lines of
{"Key": "fieldname", "Value" : "some error for fieldname"}
What is the best way to return my data and how can I get it serialised in the correct way that I need?

I suggest you use Json.NET (it is default JSON serializer for ASP.NET MVC 4 as well) and its JsonWriter:
StringWriter errorsStringWriter = new StringWriter();
JsonWriter errorsJsonWriter = new JsonWriter(jsonStringWriter);
errorsJsonWriter.WriteStartObject();
errorsJsonWriter.WritePropertyName("fieldname");
errorsJsonWriter.WriteValue("some error for fieldname");
errorsJsonWriter.WritePropertyName("fieldname2");
errorsJsonWriter.WriteValue("some error for fieldname2");
...
errorsJsonWriter.WriteEndObject();
errorsJsonWriter.Flush();
You can return JSON generated this way with ContentResult:
return Content(errorsStringWriter.GetStringBuilder().ToString(), "application/json");
UPDATE
Json.NET also supports dynamic JSON through JObject. In that case your code can look like this:
var jsonObject = new JObject();
jsonObject.Add("fieldname", "some error for fieldname");
jsonObject.Add("fieldname2", "some error for fieldname2");
...
Creating ContentResult in this case can look like this:
return Content(jsonObject.ToString(Newtonsoft.Json.Formatting.None), "application/json");

Related

JSON is printed with backslashes

{"externalQueryDate":"4018-11-23"}
this is my json string, which is in a column of mysql.
I get it with creditRisk.getCreditRiskDataCodeBased()
and in javascript or in swagger, i see with backslashes:
"{\"externalQueryDate\":\"4018-11-23\"}"
I can use JSON.parse in frontend but , i want to solve this is backend.
even
for
StringWriter sw = new StringWriter();
objectMapper.writer().writeValue(sw, creditRisk.getCreditRiskDataTermBased());
it writes this:
"responseCode": "\"{\\\"externalQueryDate\\\":\\\"4018-11-23\\\"}\""
I tried those
objectMapper.readTree(creditRisk.getCreditRiskDataCodeBased()).toString()
and
objectMapper.writer().writeValue(sw, creditRisk.getCreditRiskDataTermBased());
and
#JsonRawValue
#JsonValue
How can i solve this?
In mysql, it is also without slashes
If you want to parse the json string with jackson objectMapper you need to use 'read' and tell it what class to use to create the parsed object from.
So in your case you could do something like
ObjectMapper objectMapper = new ObjectMapper();
String json = "{\"externalQueryDate\":\"4018-11-23\"}";
Map map = objectMapper.readValue(json, Map.class);
System.out.print(map.get("externalQueryDate"));
I've just used a Map here as I don't know what class you're wanting to parse the json into. If you have a class with an externalQueryDate field you can read into that. You could also use #JsonFormat on the field to tell it what the date format is if you want to parse the value straight into a LocalDate field.
I suggest you write a few simple unit tests to get the hang of escaped quotes in strings. It looks like they're causing you some confusion.

Nested object JSON serialization in WebAPI

I am using .NET 4.0, MVC 4, Web API. I have following data structure:
Dictionary<Actor, Int32> TopActorToMovieCount = new Dictionary<Actor, Int32>(10);
And following entry in WebApiConfig:
config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
In my Controller, I am returning TopActorToMovieCount this way:
[HttpGet]
public HttpResponseMessage HighestMovies()
{
return Request.CreateResponse(HttpStatusCode.OK, MvcApplication.TopActorToMovieCount);
}
But the JSON output it is giving is:
{"api.Models.Actor":137,"api.Models.Actor":125,"api.Models.Actor":99,"api.Models.Actor":96,"api.Models.Actor":83,"api.Models.Actor":82,"api.Models.Actor":81,"api.Models.Actor":79,"....
Why it is not giving JSON structure for object of Actor?
I am sure that I am missing something, bout couldn't figure out. I tried adding following, but it didn't work:
config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/json"));
PS: When I switch to XML output, it works fine.
See similar question here: Not ableTo Serialize Dictionary with Complex key using Json.net
In this case, you are using "Actor" as the Key of your dictionary. Dictionary stores key/value pairs. So when creating the JSON response, it interprets the "Actor" as a key which is converted to a string, and the "Int32" as the value thus giving you
{"api.Models.Actor":137} or {key:value}
because
Actor.ToString() would result in "api.Models.Actor"
Here's a link to the definition of Dictionary: https://msdn.microsoft.com/en-us/library/xfhwa508(v=vs.110).aspx

How can I define a ReST endpoint that allows json input and maps it to a JsonSlurper

I want to write an API ReST endpoint, using Spring 4.0 and Groovy, such that the #RequestBody parameter can be any generic JSON input, and it will be mapped to a Groovy JsonSlurper so that I can simply access the data via the slurper.
The benefit here being that I can send various JSON documents to my endpoint without having to define a DTO object for every format that I might send.
Currently my method looks like this (and works):
#RequestMapping(value = "/{id}", method = RequestMethod.PUT, consumes = MediaType.APPLICATION_JSON_VALUE)
ResponseEntity<String> putTest(#RequestBody ExampleDTO dto) {
def json = new groovy.json.JsonBuilder()
json(
id: dto.id,
name: dto.name
);
return new ResponseEntity(json.content, HttpStatus.OK);
}
But what I want, is to get rid of the "ExampleDTO" object, and just have any JSON that is passed in get mapped straight into a JsonSlurper, or something that I can input into a JsonSlurper, so that I can access the fields of the input object like so:
def json = new JsonSlurper().parseText(input);
String exampleName = json.name;
I initially thought I could just accept a String instead of ExampleDTO, and then slurp the String, but then I have been running into a plethora of issues in my AngularJS client, trying to send my JSON objects as strings to the API endpoint. I'm met with an annoying need to escape all of the double quotes and surround the entire JSON string with double quotes. Then I run into issues if any of my data has quotes or various special characters in it. It just doesn't seem like a clean or reliable solution.
I open to anything that will cleanly translate my AngularJS JSON objects into valid Strings, or anything I can do in the ReST method that will allow JSON input without mapping it to a specific object.
Thanks in advance!
Tonya

Couchbase - deserialize json into dynamic type

I'm trying to deserialize some JSON coming back from couchbase into a dynamic type.
The document is something like this so creating a POCO for this would be overkill:
{
UsersOnline: 1
}
I figured that something like this would do the trick, but it seems to deserialize into a dynamic object with the value just being the original JSON
var jsonObj = _client.GetJson<dynamic>(storageKey);
results in:
jsonObj { "online": 0 }
Is there anyway I can get the couchbase deserializer to generate the dynamic type for me?
Cheers
The default deserializer for the client uses .NET's binary serializer, so when you save or read a JSON string, it's just a string. GetJson will always just return a string. However, there are a couple of options:
You could convert JSON records to Dictionary instances:
var appJson = "{ \"UsersOnline\" : 1, \"NewestMember\" : \"zblock\" }";
var result = client.ExecuteStore(StoreMode.Set, "userCount", appJson);
var item = client.GetJson<Dictionary<string, object>>("userCount");
Console.WriteLine("There are {0} users online. The newest member is {1}.",
item["UsersOnline"], item["NewestMember"]);
Or you could use a dynamic ExpandoObject instance:
var appJson = "{ \"UsersOnline\" : 1, \"NewestMember\" : \"zblock\" }";
var result = client.ExecuteStore(StoreMode.Set, "userCount", appJson);
dynamic item = client.GetJson<ExpandoObject>("userCount");
Console.WriteLine("There are {0} users online. The newest member is {1}.",
item.UsersOnline, item.NewestMember);
In either case you're losing static type checking, which seems like it's OK for your purposes. In both cases you get access to the JSON properties without having to parse the JSON into a POCO though...
Edit: I wrote a couple of extension methods that may be useful and blogged about them at http://blog.couchbase.com/moving-no-schema-stack-c-and-dynamic-types

WebClient.DownLoadString is adding \" infront of my JSON data elements.How to parse it as normal JSON without \"?

I am trying to access a REST Service in my MVC application.I am calling getJSON method to get the data from a controller which internally calls the REST service which returns data in json format.But I am getting the a lot of "\ in my output of DownLoadString method and my return Json is not returning proper JSON data and hence my client side script is not able to access the JSON properties.
My Script in my view is
$.getJSON("#Url.Action("GetManufacturers", "Home")",function(data){
console.debug("Status is : "+data.Status)
});
My Action method looks like this
public ActionResult GetManufacturers()
{
string restURL ="http://mytestserver/myapi/Manufacturers";
using (var client = new WebClient())
{
var data = client.DownloadString(restURL);
//data variable gets "\" everywhere
return Json(data,JsonRequestBehavior.AllowGet);
}
}
I used visual studio breakpoints in my action method and i am seeing a lot of \"
And i checked what is coming out to my getJSON callback and the JSON tab is empty.
But my response tab has content like this
I belive if there is no \", i would be able to parse it nicely.
I used fiddler to see whether i am getting correct (JSON format) data from my REST service and it seems fine.
Can anyone help me to tackle this ? I would like to return proper JSON from my action method. Sometime i may want to read the json properties in the C# code itself. I saw some example of doing it with DataContractJsonSerializer. But that needs a concrete type to be converted to. I don't want to do that. because other clients would also access my RESTService and how will expect them to write a fake entity for this ?
You need to return the data as is:
public ActionResult GetManufacturers()
{
string restURL ="http://mytestserver/myapi/Manufacturers";
using (var client = new WebClient())
{
var data = client.DownloadString(restURL);
return Content(data, "application/json");
}
}