Unexpected character encountered while parsing value: { - serialization

I am trying to parse some JSON with Newtonsoft.JSON.JsonConvert.DeserializeObject - in fact the JSON was also generated by Newtonsoft from the same classes I am trying to deserialize into, and is definitely valid.
But it is giving me the exception: Newtonsoft.Json.JsonReaderException : Unexpected character encountered while parsing value: {.
I've made a very simplified example to show the problem.
Here is the JSON:
{
"address": {
"country": {
"name": "UK"
}
}
}
Here is a simplified model which still shows the problem:
public class Person
{
public Address Address;
}
public class Address
{
public Country Country;
public Address(string country)
{
}
}
public class Country
{
public string Name;
}
Here is the code which fails:
// Fails with Newtonsoft.Json.JsonReaderException : "Unexpected character encountered
// while parsing value: {. Path 'address.country', line 3, position 16."
Person item = JsonConvert.DeserializeObject<Person>(json);
I have checked, and this is not the same problem as C# - Unexpected character encountered while parsing value: {. Path '[0].Statistics or Unexpected character encountered while parsing API response . I have now worked out the issue (see my answer below), and it is NOT the same problem or solution as either of those two.

This short answer is, make sure that the class corresponding to the immediate parent of the path where the problem is reported (the path is 'address.country' in the above exception message; its immediate parent is 'address') has a public parameterless constructor.
So, in the above you must add a public parameterless constructor to your Address class.
Here is the Address class from the example with some comments explaining what is going on:
public class Address
{
public Country Country;
// With this present the JSON parses just fine!
public Address() { }
// Because both of the following were true:
// 1) the name of a parameter here matches the name of a field to be populated and
// 2) there was no public parameterless constructor
// this was constraining what could appear in the JSON to populate "address"!
public Address(string country)
{
}
}

Related

Linqpad: LINQPad.Util.Cache throws error if query file is modified, saved and re-run. "Cannot load type" error

Using the amazing LinqPad with a C# script. Get an error using the Util.Cache storing a custom class declared in the same script. How to resolve, other than restarting LinqPad please?
Reproduce error:
Add any char to the comment
save file
run again
Error raised:
Cannot load type 'UserQuery+IPerson' from cache.
Data
(0 items)
HelpLink null
HResult -2146233088
InnerException null
Message Cannot load type 'UserQuery+IPerson' from cache.
Source LINQPad.Runtime
StackTrace at LINQPad.Util.Cache[T](Func`1 dataFetcher, String key, Boolean& fromCache)
at LINQPad.Util.Cache[T](Func`1 dataFetcher, String key)
at UserQuery.Main(), line 3
TargetSite
RuntimeMethodInfo•••
CacheConverter.CanConvert (Type sourceType, Type targetType, HashSet<TypeType> visitedTypes)
Linqpad query code
Here is the code being run:
void Main()
{
IPerson p = Util.Cache<IPerson>(()=>new Person("Bob"), "person_bob9");
p.Dump();
// add any char after here, save re-run, error thrown: a
}
interface IPerson{string Name {get;init;}}
class Person:IPerson
{
public Person(string name)=> Name = name;
public string Name { get; init; }
}
Notes
Maybe this happens because the Person class is compiled by linqpad into a dll each time the file is modified and run. When an instance of Person is stored in a cache, this might differ from the current Person type declaration, hence the error.
i guess it works with functions
void Main()
{
var p = Util.Cache<Person>(() => AddPerson("uuuu"), "cached_user").Dump();
p.Dump();
string s = "";
}
interface IPerson
{
string Name { get; init; }
}
[Serializable]
public class Person : IPerson
{
public Person(string name) => Name = name;
public string Name { get; init; }
}
public Person AddPerson(string Name)
{
//Thread.Sleep(1000);
return new Person(Name);
}

UNWRAP_ROOT_VALUE gives an unexpected match

I'm pretty new to Jackson so apologies in advance if there's an obvious solution.
I'm writing a Jersey client and I'm trying to deserialize JSON in the following format:
{
"success": true,
"someEntity": {
"someField": 123
}
}
Now if the 'success' field didn't exist this would be pretty simple as I could just configure the ObjectMapper to use DeserializationFeature.UNWRAP_ROOT_VALUE and it'd deserialize the contents to SomeEntity.
My Response object looks like:
public class Response<T>
{
private boolean success;
private T entity;
public T getEntity()
{
return entity;
}
public boolean isSuccess() {
return success;
}
}
Where entity would be...
public class SomeEntity
{
private int someField;
public int getSomeField()
{
return someField;
}
}
When trying to deserialize the above JSON to Response<SomeEntity> without any configuration I get: Unrecognized field "someEntity" (class Response)
I had some luck with adding #JsonProperty("someEntity") to the entity field but obviously I'd like this response class to be generic and not have to make one for every entity passed to the client.
I'm sure there's a simple solution that I'm not seeing - thanks in advance.
Edit: I've also tried using #JsonTypeInfo to no avail.

How to get JacksonXML to de-serialize embedded objects

I am writing a REST interface using Jersey and have configured it to use JacksonXML to do the JSON<->POJO conversions. I have a set of classes like this:
#JsonInclude(JsonInclude.Include.NON_NULL)
public class JsonPo {
public Long id;
public String type;
public Boolean committed;
public String owner;
// ...
Which is referenced in my main class like this:
#JsonInclude(JsonInclude.Include.NON_NULL)
public class JsonPoReq {
public Long id;
public String pathstring;
public int firstrecord;
public JsonPo obj;
// ...
And the REST resource of course looks like this:
#POST
#Path("path")
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
public Response byPath(JsonPoReq req) {
// ...
The serialization (POJO->JSON) works fine. The properties in the JsonPo object get serialized in a JSON object as you would expect.
The reverse doesn't work. Even if I feed the serialized string back. What happens is the obj property is always set to null.
EDIT: As requested the following is what the JSON string looks like:
{
"id" : 2,
"pathstring" : "/a/b/c",
"firstrecord" : 0,
"obj" : {
"id" : 2,
"type" : "ProtoObject",
"committed" : false,
"owner" : "admin"
}
}
I have been going through the JacksonXML Annotations to see how to fix this but I haven't been able to come up with anything. Is there some other step I am supposed to take?
UPDATE: Problem was not real. Some application code was being invoked that I didn't notice was clearing the object.

mono rises unexpected compiler errors

I have the following class
public class LockRequest
{
public int Id { get; set; }
public string TypeName { get; set; }
public bool Ok { get; set; }
public LockRequest ( int id, string t)
{
Id = id;
TypeName = t;
}
}
Then, it's referenced in a delegate, as follows
private static void ReceiveLockRequest<LockRequest>(PacketHeader header, Connection connection, LockRequest input )
{
LockRequest lr = new LockRequest(1, "SomeTypeName" );
Console.WriteLine( String.Format ( "{0} ", input.TypeName) );
}
When compiling, both lines from the delegate rises compiler errors.
The line with the "new()", produces "Cannot create an instance of the type class 'LockRequest' because it does not have the 'new()' constraint.
The line which would show some of the input data gives "The type 'Lockrequest' does not contains a definition for 'TypeName' and no extension method 'TypeName' ... etc".
Could someone explain why is this behaviour?
My dev environment is Ubuntu 10.04 (64 bits) and Monodevelop 2.8.6.3
TIA
Could add some info.
I changed the name of the class, and the thing compiled. The whole class is to be serialised by ProtoBuf, so it must be decorated with attributes. Here are is a sample
[ProtoContract]
public class Foo
{
[ProtoMember(1)]
public int { get; protected set; }
[ProtoMember(2)]
public string TypeName { get; protected set; }
...
Just after I added the attributes, mono stop compiling. Same erors raise again.
To test it, I commented the attributes, do a Clean All, an recompile. The errors raise again, as if MonoDevelop cached them.
I need some help more than after the initial post.
2013-10-31
Thank you, Jester. It´s an event handler, from NetworkCommDotNet library.
My faults:
1) The first error (members not recognized) raises from the fact that (somewhat astobishing) the "input" argument comes as a plain object. Casting it in another method does the trick.
2) The error regarding the instanciation: the delegate definition in the library have a where clause wich states that T must be class, but no the new() constraint.
That's not a delegate, that's a generic method.
It's not clear what you want to do and why do you need a generic method.
If you really do, then try something along the lines of:
private static void ReceiveLockRequest<T>(PacketHeader header, Connection connection, T input) where T:LockRequest
PS: your development environment is very old, consider upgrading.

Handle Conversion Error using Resource Files

I have Internationalized my MvC4 application.Inside model there is one property
public float Fuels{ get; set; }
When i typed string value inside textbox corresponding to this property,I got a validation error 'The value 'ff' is not valid for Fuels.'.But i want to handle it using resource file.If i have selected arabic then validation error should come in arabic..
I got required message using the following code
[Required(ErrorMessageResourceType = typeof(#Application.Resources.Admin.Country),
ErrorMessageResourceName = "FuelReq")]
I have tried the following way:-
public class FLoatAttribute : DataTypeAttribute
{
private const string defaultErrorMessage = "{0} is required.";
public FLoatAttribute()
: base(defaultErrorMessage)
{
}
public override string FormatErrorMessage(string name)
{
return string.Format(ErrorMessageString, name);
}
public override bool IsValid(object value)
{
float objFloat;
return float.TryParse(Convert.ToString(value), out objFloat);
}
}
and tried using regular expression inside model.But it didn't worked.
Pls help me.