Date Format Issue When Using JavaScriptSerializer().Serialize() |
We should parse the Date Format into a required format before sending it to
the function. That is instead of sending DateTime, it will be better to
change to a desired forma and then send it to the said function. That
solved my issue.
|
Serialize PHP => Unserialize JAVA / Serialize for php in string format |
You can't natively read one languages serialised objects with another
language (languages each have their own serialisation protocols/format,
there is no guarantee they can read one-anothers format), Java serialised
objects are serialised to a binary format and PHP your provided text
format.
There are libraries such as Google's protocol buffers that you can use,
they don't officially support PHP, however there are 3rd party libraries
which provide Protocol Buffer support for PHP.
Protocol buffers are Google's language-neutral, platform-neutral,
extensible mechanism for serializing structured data – think XML, but
smaller, faster, and simpler. You define how you want your data to be
structured once, then you can use special generated source code to
easily write and read your
|
How to force camelcase with JavaScriptSerializer? |
You can use a camel case resolver from Newtonsoft.Json.Serialization;
On you global.asax you register it on application start
using Newtonsoft.Json.Serialization;
protected void Application_Start()
{
config.Formatters.JsonFormatter.SerializerSettings.ContractResolver =
new CamelCasePropertyNamesContractResolver();
}
|
Convert JSON to XML using JavaScriptSerializer in c# |
JavaScriptSerializer.DeserializeObject cast json string to
Dictionary<String, Object>.
Dictionary is not supported by XMLSerializer. So if you're creating json
yourself, you might want to change its structure and use
JavaScriptSerializer.Deserialize<T> method to cast it to specific
class and latter serialize it to XML.
|
JavaScriptSerializer unexpected output |
wrong approach - now I use a simple stringbuilder.
foreach (DictionaryEntry entry in xSet)
{
result.AppendFormat("{0}: '{1}',", entry.Key,
HttpUtility.JavaScriptStringEncode(entry.Value.ToString()));
}
|
JavaScriptSerializer for windows phone 8 |
You could use JSON.NET instead of JavaScriptSerializer: it has better
performance and supports .NET 2, .NET 3.5, .NET 4, Silverlight and Windows
Phone.
Here is the equivalent of your code with JSON.NET:
var dataObject =
JsonConvert.DeserializeObject<MyResponseClassObject>(result);
return dataObject;
|
.NET 3.5 JavaScriptSerializer and DateTimeOffset serialization |
The bigger problem is when you serialize Date value and Deserialize it
back, you lost DateTimeOffset and the Deserialized value is in UTC time.
So let's start from begining, what kind of serializer/deserializer you
user?
.Net / Json.Net / LightJson / ...
|
JavaScriptSerializer namespace issue |
JavaScriptSerializer is situated in System.Web.Extensions Assembly. You
should add it to your project references.
You can get this information in MSDN
Assembly: System.Web.Extensions (in System.Web.Extensions.dll)
|
JavaScriptSerializer UTC DateTime issues |
JavaScriptSerializer, and DataContractJsonSerializer are riddled with bugs.
Use json.net instead. Even Microsoft has made this switch in ASP.Net MVC4
and other recent projects.
The /Date(286769410010)/ format is proprietary and made up by Microsoft.
It has problems, and is not widely supported. You should use the
1979-02-02T02:10:10Z format everywhere. This is defined in ISO8601 and
RF3339. It is both machine and human readable, lexically sortable, culture
invariant, and unambiguous.
In JavaScript, if you can guarantee you will be running on newer browsers,
then use:
date.toISOString()
Reference here.
If you want full cross-browser and older-browser support, use moment.js
instead.
UPDATE
As an aside, if you really want to keep using JavaScriptSerializer, you
could deserialize
|
JavaScriptSerializer How to Deserialize an identifier with space |
You can still use built-in types, but you'll need to use
DataContractJsonSerializer instead of JavaScriptSerializer, and add the
appropriate DataContract and DataMember attributes - the implementation is
a bit different, but still pretty straightforward.
One thing - your Sold property is boolean, but your JSON sample has a
string there - booleans are valid JSON types, so you can remove the quotes.
Some working code:
JSON:
[{"AdvertId":"1234567","Price Original":"500","Sold":false}]
C#:
var ser = new DataContractJsonSerializer(typeof(Sample[]));
using (var ms = new MemoryStream(Encoding.UTF8.GetBytes(JSON))) {
Sample[] s = (Sample[])ser.ReadObject(ms);
}
[DataContract]
public class Sample {
[DataMember]
public int AdvertId { get; set; }
[DataMember(Name = "Price Ori
|
deserialization with the JavaScriptSerializer is missing fields |
You have list of objects with one property json_content in your JSON, but
expect list directly containing json_content objects.
Most likely fix is to remove intermediate object from JSON (if you control
it):
[
{
"city": "city 1",
"myAge": 15
},...
];
If you don't control JSON add outer class:
class JsonOuterContent
{
public JsonContent json_content;
}
List<JsonOuterContent> list = serializer
.Deserialize<List<JsonOuterContent>>(myContent);
|
Mocking JavascriptSerializer results in error |
JavaScriptSerializer.Serialize is not virtual so cannot be mocked. Instead
your wrapper interface and class should contain a Serialize method which
you can mock.
For example:
public class JavascriptSerializerWrapper : IJavascriptSerializerWrapper
{
public string Serialize(object toSerialize)
{
var serializer = new JavaScriptSerializer();
return serializer.Serialize(toSerialize);
}
}
Then your test can use it like so:
m_JavascriptSerializerWrapper.Setup(x =>
x.Serialize(userInfoDTO)).Returns(serializedObject);
|
c# JavaScriptSerializer on JSON containing string + dictionary |
I can't answer it using JavaScriptSerializer but you can do it using
json.Net and Linq
var jObj = JObject.Parse(json);
var fields = jObj["fields"]
.Select(x => new Field
{
Id = (int)x["id"],
Type = (string)x["type"],
Value = x["value"] is JValue
? new
Dictionary<string,string>(){{"",(string)x["value"]}}
: x["value"].Children()
.Cast<JProperty>()
.ToDictionary(p => p.Name, p
=> (string)p.Value)
})
.ToList();
private class Field
{
public int Id { get; set; }
public string Type { get; set; }
public Di
|
How do I Deserialize the following JSON string with the .NET JavaScriptSerializer class? |
Your json is a little bit weird, since the value of newValue and oldValue
is string, not object. It seems that they are double-serialized. Below
code works (by first deserializing the whole json string, and then the
old/new/values)
var jArr = JArray.Parse(json);
var anon = new { id = 0, desc = "" };
var items = jArr.Select(item => new
{
NewValue =
JsonConvert.DeserializeAnonymousType(item["newValue"].ToString(),anon),
OldValue =
JsonConvert.DeserializeAnonymousType(item["oldValue"].ToString(),anon)
})
.ToList();
|
JavaScriptSerializer.Deserialize() skip property if cannot parse it |
Yes, it is possible to control the deserialization process by writing a
custom JavaScriptConverter class:
public class PersonConverter : JavaScriptConverter
{
public override object Deserialize(IDictionary<string, object>
dictionary, Type type, JavaScriptSerializer serializer)
{
Person person = new Person();
foreach (string key in dictionary.Keys)
{
var value = dictionary[key];
switch (key)
{
case "Name":
person.Name = (string)value;
break;
case "Age":
{
if (value is int)
{
person.Age = (int)value;
}
|
C# JavaScriptSerializer and DateTime.MinValue crossing timezones |
Just pass them around as strings instead of DateTimes. yyyy-MM-dd hh:mm:ssZ
will make it culture-neutral and cast it to UTC, which will ignore all time
zones. This is used in the C# DateTime as code u.
|
Error during serialization or deserialization using the JSON JavaScriptSerializer in KendoUI |
Try placing this setting in the web.config of your project:
<configuration>
<system.web.extensions>
<scripting>
<webServices>
<jsonSerialization maxJsonLength="50000000"/>
</webServices>
</scripting>
</system.web.extensions>
</configuration>
|
JavaScriptSerializer : Unable to deserialize object containing HashSet field |
What is the solution to this?
Use Json.Net. This code works...
Filter f = new Filter();
f.DataSources = new HashSet<int>() { 1, 2 };
string json = JsonConvert.SerializeObject(f);
var g = JsonConvert.DeserializeObject<Filter>(json);
EDIT
DataContractJsonSerializer seems to work too...
DataContractJsonSerializer dcjs = new
DataContractJsonSerializer(typeof(Filter));
var g2 = dcjs.ReadObject(new MemoryStream(Encoding.UTF8.GetBytes(json))) as
Filter;
|
Issue while converting linq result to JSON in MVC4 using JavaScriptSerializer |
Departments= jss.Serialize(
db.Departments.Select(d => new{
DepartmentId = d.DepartmentId,
DepartmentName = d.DepartmentName
})
);
|
System.Web.Script.Serialization.JavaScriptSerializer Sharepoint Online event receiver solution not working |
Check suggestions from the Using System.Web.Extensions in Crm plugin
thread.
If your issue is different, enable the VERBOSE logging mode and share the
corresponding LOG info here.
|
How to serialize all li#id within an ul with jquery.serialize()? |
serialize() is to encode a set of form elements as a string for submission.
Try using .each() and loop all li elements inside div:
$(document).ready(function(){
var myaudiotracks = new Array();
jQuery('#audio_list li').each(function(){
myaudiotracks.push($(this).attr("id").split("trackid_")[1]);
});
console.log(myaudiotracks);
});
DEMO FIDDLE
|
How serialize one listener and don't serialize other listener of same event |
Frankly, I would strongly advise: do not serialize events... ever. That is
pure implementation, where-as serialization should be talking data.
With BinaryFormatter (which is, I assume, what you are using) the only way
to selectively serialize this would be to implement ISerializable and do
all the work yourself, but frankly I strongly advise against it - just as
strongly as I advise against serializing events in the first place (of
course, I also routinely caution people about using BinaryFormatter in the
first place, especially if the intent is to store the data somewhere - too
many horror stories...)
|
Python - Chaining methods: returning `self` vs returning a new cloned object |
Django does this so that the base query can be kept around and reused,
without inheriting changes from a future "child" query, like your exclude()
on your filter(). I'm guessing somebody tried storing queries for later,
and realized that didn't work well without copying.
I cloned the django repo and did a quick git log on
django/db/models/query.py, searching for the phrase clone.
The patch that introduces this change is here:
https://github.com/django/django/commit/d4a3a4b
|
Oracle Query is returning value when setting value to it, but not returning value when passing date value |
Since you're already forcing the date format, you can use the following
query instead:
SELECT INCIDENT_ID
FROM INC_SM1 I
WHERE
I.CLOSE_TIME >= START_DATE
AND I.CLOSE_TIME < END_DATE
|
JavaScript, stringify, replacer - returning undefined vs. returning nothing |
If you don't provide an explicit return, the return value is undefined.
Your second function always returns undefined, in other words. Because the
function always returns undefined, there'll never be anything included in
the JSON stringified result, so the overall effect is that you get
undefined.
It's sort-of an anti-pattern to do this:
if (something) {
return whatever;
}
else {
return somethingElse;
}
Your first function would be more idiomatic as:
str = JSON.stringify(o,function(k,v) {
return Object.isSealed(this) ? undefined : v;
});
edit — note that JSON.stringify() calls your replacer function first
with an empty key, and "v" equal to this a new wrapper object containing
the object to be stringified (and note that that object is not sealed).
That is, before chec
|
Web API Serialize XML |
It says response.Content.ReadAsAsync().Result;
Are your sure result is populated before you return it?
In the debugger you have one behaviour, outside another.
Try turning ReadAsAsync off to see if it is the culprit.
|
How to serialize non-associated models? |
I figured out how to do it.
I needed to wrap my method call like such:
def all_model_two
object.get_all_model_two.active_model_serializer.new(object.get_all_model_two)
end
|
GWT: How to serialize objects |
All the code you need to look at is in the RemoteServiceServlet.java. Focus
on the processCall method.
The RPC.decodeRequest(payload, ...) will give you a RPCRequest object which
includes the method to be called and the deserialized parameters.
To encode the response focus on RPC.invokeAndEncodeResponse() and
RPC.encodeResponseForSuccess() methods.
[EDITED]
In client-side it's worth to take a look to the proxy classes generated by
the RPC generator, concretely the YourService_Proxy.java file. Generated
files are left somewhere in your project's folder structure after compiling
a project (you can indicate this folder with the -gen though).
The interesting code is in in the RemoteServiceProxy, looking at the
createStreamWritter method, you can see how to serialize your objects. In
the
|
Serialize QFileInfo |
There is no standard way to do that. You can define your custom QDataStream
operators as showed in this answer, or you can write your own functions to
convert QFileInfo to QVariant and back, and use QVariant serialization. In
all these ways you need to break up the data into primitive units, yes.
However I think serializing QFileInfo is pointless. You should use
QFileInfo::absoluteFilePath() to get the file's path and serialize that
path instead. A new QFileInfo object can be easily constructed from that
path if your receiving code is running on the same machine.
If your code is running on the other machine, you couldn't use deserialized
QFileInfo even if it would be possible. It's because QFileInfo may or may
not store information about file. When you run e.g. QFileInfo::isFile, it
may
|
Can't serialize form |
To have a serialized form, you have to add a name attribut to your input
field like this (http://jsfiddle.net/3tKUh/2/) :
<form id="myform">
<div class="field">
<label for="name" id="namelabel">Name</label>
<input type="text" name="name" id="name" class="req" autofocus>
</div>
<div class="error" id="name_error">
</div>
<div class="field">
<label for="email">Email</label>
<input type="text" name="email" id="email" class="req">
</div>
<div class="error" id="email_error">
</div>
<div class="field">
<label for="message" name="message"
id="message">Message</label>
<textarea></textarea>
</div>
<div class="field">
<input type="submit" value="submit" id="send">
|
How can Serialize XML in Android? |
I think Dom can't Work for my XML Beacause image tag contain information
that use for dispaly images.me just split image and video tag in two array
.
for Split use regex its carefylly work But I want access to Fields in Image
tag ..for Example :
<Image ImageID="1000032"
**StoredFilename**="42825125-8002-4d28-ba90-9889de5e4e91.jpg"
ImageName="bPanda" /></Images>
this tag include StoredFiledname that Spilt it in array
|
Serialize Integer[] |
You can convert int[] into byte[] with ByteBuffer
int[] a = { 1, 2, 3 };
ByteBuffer bb = ByteBuffer.allocate(a.length * 4);
bb.asIntBuffer().put(a);
byte[] bytes = bb1.array();
send byte[] to server and convert it back to int[]
int[] a = new int[bytes.length / 4];
ByteBuffer.wrap(bytes).asIntBuffer().get(a);
|
serialize an interface wcf |
If you look at the definition of KnownTypeAttribute, you cannot apply to
Interfaces.
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct, Inherited
= true, AllowMultiple = true)]
public sealed class KnownTypeAttribute : Attribute
"Known types can be associated only with classes and structures, not
interfaces." from here:
http://msdn.microsoft.com/en-us/library/ms730167.aspx
|
How to serialize ObservableCollection in C#? |
ObservableCollection<T> implements IEnumerable<T> so you should
be able to convert it to a List<T> or T[] simply enough with the
ToList()/ToArray() extensions. Both of which can be serialized with the
DataContractSerializer without issue (as long as the attributes a properly
applied).
|
XML serialize without overwriting |
It sounds like you should create a List<Actor> - you can then start
with a list of one entry, serialize that list, then next time round
deserialize the list, add an actor, and then serialize again so you'll have
two entries in the list the following time, etc.
|
Why Serialize fails to do its job? |
Basically, JavaScriptSerializer doesn't support that pattern of conditional
serialization. So: use one that does - fortunately, Json.NET does support
this, and works fine:
string jsonData = JsonConvert.SerializeObject(pageModelInstance);
(no other changes needed, although you can safely remove the [Serializable]
- that isn't needed)
|
Able to de-serialize a xml document but cannot serialize to the same document |
If it is not possible to modify the existing class and you don't want to
use XMLDocument, XDocument, etc to explicitly produce the XML, then here
are 2 main techniques you can use:
create a companion class which has the correct XML attributes and types on
it which you use just for serialization...this means you have to copy the
data from your original class type into the new one, then serialize the new
class
use your original class and create XmlElements by using a dummy XmlDocument
This example shows both techniques in operation.
Also note how the MemoryStream uses a StreamWriter so that the XML gets
written out explicitly as UTF-8 (the encoding="UTF-8" gets put in for you).
See default encoding for XML is UTF-8 or UTF-16? ... for the different ways
you might want to encode your XML
|
How to serialize ANY Object into a URI? |
I think, solution number 4 is OK. It is simple to understand and clear.
I propose similar solution in which we can use @JsonAnySetter annotation.
Please, see below example:
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.databind.ObjectMapper;
public class JacksonProgram {
public static void main(String[] args) throws Exception {
C1 c1 = new C1();
c1.setProp1("a");
c1.setProp3("c");
User user = new User();
user.setName("Tom");
user.setSurname("Irg");
ObjectMapper mapper = new ObjectMapper();
System.out.println(mapper.convertValue(c1, UriFormat.class));
System.out.println(mapper.convertValue(user, UriFormat.class));
}
}
class UriFormat {
private StringBuilder build
|
Returning 'nil' from a Lua function in C vs returning 0 values |
Yes, this is perfectly valid. If you're trying to request/assign more
return values than there are (no matter whether you try to get one or ten),
you'll get nil for the undefined ones (i.e. those not returned).
function test1()
return 5
end
local a, b = test1()
-- a = 5, b = nil
function test2()
return 1, 2
end
local c, d, e = test2()
-- c = 1, d = 2, e = nil
function test3()
end
local f, g = test3()
-- f = nil, g = nil
You probably can't find it in Lua's source because it's no special case or
anything. It's just Lua's generic way to handle return values.
Update:
The difference you've noticed when trying to print return values is the
fact that this is not just an assignment. Of course there is a slight
difference between returning nil and returning nothing at all - and it
|
serialize & before_save in Rails 4 |
I believe this append because the value of extensions is serialized while
the model is validated by Rails, and your process_extensions method is
called later (before the model is saved) and does not act as expected
Try to use before_validate instead
before_validate :process_extensions
|