3

since JSON ist a format that can be written as string it has to be interpreted by an library or sometimes native by the language itself.

In the older versions of C# there is nothing like that. Using the library LitJSON I have the following problem I have a class called Vector3 containing 3 float values (not double).

public class Vector3 {
 public float x{get;set;}
 public float y{get;set;}
 public float z{get;set;}
}

Using the following snipped of code with LitJSON it shoudl actually fill an instance of Vector3 with values.

Vector3 test = JsonMapper.ToObject<Vector3>("{'x':1.0,'y':1.0,'z':1.0}");

But an error occures 'Can't assign value (type Single.Double) to System.Single'

It seems it only knows double but no float :/

Any solution for this?

marius
  • 1,118
  • 1
  • 18
  • 38

3 Answers3

5

Had the same problem, finally found a solution. Add these lines of code before your "ToObject" / "ToJson"

JsonMapper.RegisterExporter<float>((obj, writer) => writer.Write(Convert.ToDouble(obj)));
JsonMapper.RegisterImporter<double, float>(input => Convert.ToSingle(input));
Martin
  • 51
  • 1
  • 1
3

I wanted to comment but my reputations are < 50.

I was using LitJson in Unity3D (scripting language Mono C#). I faced the same problem while parsing the json to an object which have lot of float mebmbers. I have added float support to LitJson library. Let me know if you still require this.

Mazhar
  • 366
  • 1
  • 2
  • 13
  • have you managed to do this? i would be interested into the solution – marius Dec 03 '14 at 14:00
  • 2
    You can download updated LitJson library from [here](http://kdpr.byethost24.com/LitJson-float-support.unitypackage) – Mazhar Dec 05 '14 at 11:14
2

From what I have seen from their source code on Github the library supports Double and not Single

extracts from Jsondata.cs from their library

#region Fields
private IList<JsonData> inst_array;
private bool inst_boolean;
private double inst_double;
private int inst_int;
private long inst_long;
private IDictionary<string, JsonData> inst_object;
private string inst_string;
private string json;
private JsonType type;
Anand
  • 116
  • 1
  • 8
  • that's what I figgured out aswell, but the question is why... I'm trying to write a workaround but it's not working to well till now :/ – marius Feb 13 '14 at 00:36
  • Cant you use double inside your application? That seems to be a straightforward solution. – Anand Feb 13 '14 at 00:54
  • Well if I could have, I wouldn't ask for it here :P . I guess there is no fast solution for this, so i really have to rewrite alot of my code... thank you anyway! – marius Feb 13 '14 at 11:06