Problems try encode entity to json - json

im try encode an Doctrine entity as JSON string, to send as Ajax response.
So, i check the doc: The Serializer Component
I try with this code:
$em = $this->getDoctrine()->getManager();
// Get the entities repository
$sesiones_registradas = $em->getRepository('AuditBundle:AuditSession')->findAll();
// Instance the object
$serializer = new Serializer(array(new JsonEncoder()),array(new GetSetMethodNormalizer()));
// Convert only an item
foreach($sesiones_registradas as $sesion){
echo $serializer->normalize($sesion,'json');
break;
}
// Stop script
die();
Last code, fails saying:
Could not normalize object of type
AppsManantiales\AuditBundle\Entity\AuditSession, no supporting
normalizer found.
And if change $serializer->normalize($sesion,'json') by $serializer->serialize($sesion, 'json'); The error message is:
Serialization for the format json is not supported
Any ideas ?.

Your problem come from the fact you inverted both normalizers and encoders.
The line:
$serializer = new Serializer(array(new JsonEncoder()),array(new GetSetMethodNormalizer()));
must be:
$serializer = new Serializer(array(new GetSetMethodNormalizer()), array(new JsonEncoder()));

Use the JMS Serializer Bundle
The docs can be found here: http://jmsyst.com/bundles/JMSSerializerBundle

Related

Dart/Flutter : Avoid Method parsing in Map , when converting to JSON?

In Dart / Flutter , when converting a map (which contains a Closure method) to json using jsonEncode , I getting following error :
Converting object to an encodable object failed: Closure: () => dynamic
The Map having :
orderedMap1["fooddelete"] = () => deleteItemFunction(
singleitem["orderId"], singleitem["id"], singleitem["shopId"]);
If commented above line , then jsonEncode works , else throwing above error .
How to instruct the jsonEncode to skip the closures when parsing Map to Json ?
It seems highly questionable to store closures in the same Map that you want to encode to JSON, but if you must, you can encode a filtered copy of it instead:
var encoded = jsonEncode({
for (var entry in orderedMap1.entries)
if (entry.value is! Function) entry.key: entry.value,
});
I suppose you alternatively could use jsonEncode's toEncodable parameter to convert closures to something else, although I'm not sure what good that would do you since there's nothing the recipient could do with it. The following will replace closures with null:
var encoded = jsonEncode(orderedMap, toEncodable: (value) {
if (value is Function) {
return null;
}
throw UnsupportedError('Cannot convert to JSON: $value');
});
option1: remove "fooddelete" key using orderedMap1.remove("fooddelete") and then parse it.
option2: put your Closure inside the double quotation. so you can save it as String.

Symfony2 - FOSRestBundle - Custom Serializer or JSON Output

How do you create a custom JSON output with FOSRestBundle?
The code already has methods which are used to convert entities and paginated result sets to JSON. As well as generate unique URLs to view/edit the entities in the outputted JSON.
How can these be used with FOSRestBundle?
Example of custom method to convert Bars to JSON output:
$json = $this->getJsonFactory('Bar')
->dataTableFormat($data);
return $this->jsonResponse($json);
How can this custom method be used as the output for JSON from view?
$data = $this->getDoctrine()->getRepository('Foo:Bar')
->findAll();
$view = $this->view($data, 200)
->setTemplate("Foo:Bar:index.html.twig")
->setTemplateVar('bars')
;
JMSSerializerBundle is available if it helps.
Using custom handlers this is possible, see docs: http://symfony.com/doc/master/bundles/FOSRestBundle/2-the-view-layer.html#custom-handler
Working example:
$handler = $this->get('fos_rest.view_handler');
if (!$handler->isFormatTemplating($view->getFormat())) {
$templatingHandler = function ($handler, $view, $request) {
$data = $this->getJsonFactory('Bar')
->dataTableFormat($$view->getData());
$view->setData($data);
return $handler->createResponse($view, $request, 'json');
};
$handler->registerHandler('json', $templatingHandler);
}
The $templatingHandler method handles calling the JsonFactory and setting the formatting of data for json output.

Send JSON object in setVlaue() of PropertyInfo class

When I pass a string value in setValue() it calls the web service perfectly. Instead, if I pass a JSON object it shows the "cannot serialize" error. I want to send the JSON object in setValue(). Could somebody help me?
SoapObject request1 = new SoapObject(NAMESPACE, METHOD_NAME);
PropertyInfo unameProp = new PropertyInfo();
unameProp.setName("param");
unameProp.setValue(data);
unameProp.setType(String.class);
request1.addProperty(unameProp);
allowAllSSL.allowAllSSL();
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.setOutputSoapObject(request1);
HttpTransportSE ht = new HttpTransportSE(URL, 20000);
ht.call(SOAP_ACTION, envelope);
In the line 4, i added toString() to solve the issue and the issue has been resolved.
JSON object:
JSONObject param = new JSONObject();
param.put("loginid", email.toString().trim());
param.put("password", password.toString().trim());
line 4 :
unameProp.setValue(param.toString());

How to convert a stream back to json?

In a .NET 3.5 Compact Framework / Windows CE app, I need to consume some WebAPI methods that return json. RestSharp looks like it would be great for this, except that it's not quite CF-ready (see Is Uri available in some other assembly than System in .NET 3.5, or how can I resolve Uri in this RestSharp code otherwise? for details).
So, I will probably use HttpWebRequest. I can return the value from the WebAPI methods with this code:
string uri = "http://localhost:48614/api/departments";
var webRequest = (HttpWebRequest)WebRequest.Create(uri);
var webResponse = (HttpWebResponse)webRequest.GetResponse();
if ((webResponse.StatusCode == HttpStatusCode.OK) && (webResponse.ContentLength > 0))
{
StreamReader reader = new StreamReader(webResponse.GetResponseStream());
MessageBox.Show("Content is " + reader.ReadToEnd());
}
else
{
MessageBox.Show(string.Format("Status code == {0}", webResponse.StatusCode));
}
...but in order to use what's returned from reader.ReadToEnd():
...I need to convert it back to json so that I can then query the data with LINQ to JSON using either JSON.NET (http://json.codeplex.com/) or SimpleJson (http://simplejson.codeplex.com/)
Is that realistically possible (converting StreamReader data to JSON)? If so, how?
UPDATE
I'm trying to deserialize the "json" (or string that looks like json) with this code:
string uri = "http://localhost:48614/api/departments";
var webRequest = (HttpWebRequest)WebRequest.Create(uri);
webRequest.Method = "GET";
var webResponse = (HttpWebResponse)webRequest.GetResponse();
if ((webResponse.StatusCode == HttpStatusCode.OK) && (webResponse.ContentLength > 0))
{
StreamReader reader = new StreamReader(webResponse.GetResponseStream());
DataContractJsonSerializer jasonCereal = new DataContractJsonSerializer(typeof(Department));
var dept = (Department)jasonCereal.ReadObject(reader.ReadToEnd());
MessageBox.Show(string.Format("accountId is {0}, deptName is {1}", dept.AccountId, dept.DeptName));
}
...but get two err msgs on the "var dept =" line:
0) The best overloaded method match for 'System.Runtime.Serialization.XmlObjectSerializer.ReadObject(System.IO.Stream)' has some invalid arguments
1) Argument '1': cannot convert from 'string' to 'System.IO.Stream'
So reader.ReadToEnd() returns a string, and DataContractJsonSerializer.ReadObject() expects a stream, apparently. Is there a better approach for this? Or, if I'm on the right track (although currently a section of track has been removed, so to speak), how should I get past this hurdle?
UPDATE 2
I added the System.Web.Extensions reference and then "using System.Web.Script.Serialization;" but this code:
JavaScriptSerializer jss = new JavaScriptSerializer();
var dept = jss.Deserialize<Department>(s);
MessageBox.Show(string.Format("accountId is {0}, deptName is {1}",
dept.AccountId, dept.DeptName));
...but the second line fails with:
"Type 'bla+Department' is not supported for deserialization of an array."
What type should receive the call to jss.Deserialize()? How is it defined?
Well,
the ReadToEnd() method is used to read the stream into a string and output it. If you need a stream out to pass it to a method requiring a stream, you shouldn't use this method.
From what I read on this page , it seems the BaseStream property of your reader would be more appropriate to use then.

Json dynamic string list

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");