mtschoen / jsonobject Goto Github PK
View Code? Open in Web Editor NEWThe JSONObject class/library for Unity
License: MIT License
The JSONObject class/library for Unity
License: MIT License
Hello,
I'm on Unity 2017.3.0f3 and get this error after importing your repo :
JSONObject/JSONTemplates.cs(31,14): error CS0029: Cannot implicitly convert type
void' to
bool'
Any idea where does that come from ?
Json
{
"id": 186,
"device_name": "samsung SM-G900F db5a9b3e6036deb23e2491f29700045a",
"longitude": 121.00001,
"latitude": 31.00001
}
And when it's been tracked in the Unity Editor
string result = System.Text.Encoding.UTF8.GetString (buffer); //<--this result is fine, it's identical to the json string above.
JSONObject obj = new JSONObject (result);
// ^ this obj is not. the latitude is still 31.00001 but the longitude is now 121. It loses precision.
How to fix it? Is it a bug?
What platforms does it support?
try
{
// 这个不应该抛异常,应该是一个空的object。
JSONObject emptyJsonObject = new JSONObject("{}");
Debug.Log(emptyJsonObject.ToString());
}
catch (Exception e)
{
Debug.LogError("JSONObject有bug,不支持“{}”");
Debug.LogException(e);
}
try
{
// 这个不应该抛异常,应该一个空的list
JSONObject emptyArray = new JSONObject("[]");
Debug.Log(emptyArray.ToString());
}
catch (Exception e)
{
Debug.LogError("JSONObject有bug,不支持“[]”");
Debug.LogException(e);
}
This is one of "JavaScript" like library that I'm looking for. JavaScript and C# are my favorite languages but using JSON in C# is pretty shitty.
This library do not require something like "pre-defined" json scheme, I can use it dynamically just like JavaScript I always do, and that is the nature of JSON I think. Simple, extendable, easy!
Thank you for create this awesome library. Thanks!
When you read this, you can close this.
I have a Json Object that contains a Json object, after the encoding I end up with a string containing a double encoded JSON, after trying to parse it with your lib I notice that the inner JSON isn't parsed and you Lib does not support the parsing of double encoded JSONs, could you add the feature to escape JSON strings in your lib?
I think it would be extremely helpful if we had some Unit-tests, especially for lesser-used functions like Animation/Keyframe serialization and special characters.
Hi,
I love JSONObject and use it for some projects. I now want to integrate it into an open-source projects under M.I.T. license and was searching for your license information.
It is possible to use and publish the code with a clear reference to the original source and this repo?
BR and thanks again for your great work.
Tom
Hello!
I'm working on using a JSON file in unity. i'm really interested by your work.
sadly, I can't manage to import in Unity without facing a lot of issues.
First error is that he refuses to read parameter specifier. If i define those parameters just after it works. But then I got other errors popping. Do you perhaps have some unity package that i can import in my unity?
Thank you very much for you help!
Soulwax
Trying to parse this incorrect JSON string:
{"Parent":{"MyFloat":12,8}}
does not result in an error. Instead, it returns a Type.Object where the sizes of list
and keys
differ (due to SafeAddChild()
being called at some point). Is this something the user should expect and intercept/check in his code? My understanding is that a Type.Object is always a key/value pair, not just a key, so these List<>
's should always be the same size.
The source of that JSON test string is an incorrect export from some other tool (=localization misinterpretation of the value "12.8"). For "12,8", I'd expect maybe a partial JSON being returned (with MyFloat==12), but also yielding an error due to the dangling "8". I tried https://jsonformatter.curiousconcept.com/ , and it detects the error for all RFC specs.
A previous version of JSONObject we used (I think it was somewhere around 1.4) also did not throw an error, but did at least return a (syntactically) correct object:
{
"Parent":{
"MyFloat":12,
"MyFloat":8
}
}
The current version (6418374 from 2022/02/02) outputs this with JSONChecker:
{
"Parent":{
"MyFloat":12
}
}
, but also does not indicate an error, therefore silently ignoring the incorrect "8", and returning the misaligned/unexpected JSONObject.
JSONChecker
claims everything is fine, because Stringify() explicitly checks whether keys[index]
is still in range, and simply bails out if it isn't.
EDIT: Further experimenting: This equally malformed JSON (=lhs of colon must not be a number):
{"Parent":{"MyFloat":12,8:""}}
is interpreted by JSONChecker as:
{
"Parent":{
"MyFloat":12,
"MyFloat":""
}
}
, without recognizing the error, and which is also an incorrect interpretation of the input string.
Related to the previously mentioned problems with float/string conversions with different cultural settings (German for example).
I would like to add that it's not only the parsing that is affected by the float to string / string to float conversions. It's also the serialization (Stringfy(...)) of JSONObject.
This means that if you would serialize the objects with German cultural settings you would not be able to parse the output. Or even worse, the parsing succeeds, but with the incorrect values in the resulting JSONObject.
Ex:
{"value1" : 1.5, "value2" : 2.5}
//is serialized into
{"value1" : 1,5, "value2" : 2,5}
//which in turn is parsed as
{"value1" : 1, "value2" : 2}
I do not have time to make a pull request right now, but the issues can be found on line 737, 938 and 1079. Where the following needs to be changed:
builder.Append(n.ToString());
//should be
builder.Append(n.ToString(System.Globalization.CultureInfo.InvariantCulture));
and
case Type.NUMBER: result.Add(keys[i], val.n + ""); break;
//should be
case Type.NUMBER: result.Add(keys[i], val.n.ToString(System.Globalization.CultureInfo.InvariantCulture)); break;
Change Unity-detection to include newer versions.
e.g. #if UNITY_2 || UNITY_3 || UNITY_4 || UNITY_5 || UNITY_5_3_OR_NEWER
i using huge data ( about 3~4 mega )
when runtime parsing , very long time spended
so i found BakeAsync !!!
but i dont konw BakeAsync
i have question 2
and this is my code
IEnumerator co_test(){
JSONObject tmpJo = JSONObject.CreateBakedObject ( veryBigData.text);
Debug.Log ("begin");
while (tmpJo.BakeAsync () != null) {
Debug.Log (tmpJo.str );
yield return null;
}
Debug.Log ("done");
}
thanks for your Attention
Would it be possible for you to convert this to BSD or similarly permissive license please? If I understand correctly, LGPL would restrict usage of this lib in situations where you must statically link (like iOS).
In one of our jsons there are velocity values like "16 km/h"
. The used serializer serializes it to "16 km\/h"
which is a correct possibility according to json.org. Unfortunately JSONObject doesn't remove the trailing \ when deserializing the string.
A complete example of a json dictionary:
{
"domains_detail": [1, 2, 3, 4],
"status": 2,
"wind_speed": "6 km\/h W",
"id": "WD_001",
"domains_overview": [1, 2, 3, 4],
"wind_angle": 270,
"temperature": "1°C",
"domain_id": 1
}
JsonSerializationException: Self referencing loop detected for property 'normalized' with type 'UnityEngine.Vector3'. Path '[0].fill.bounds.center.normalized.normalized'.
Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.CheckForCircularReference (Newtonsoft.Json.JsonWriter writer, System.Object value, Newtonsoft.Json.Serialization.JsonProperty property, Newtonsoft.Json.Serialization.JsonContract contract, Newtonsoft.Json.Serialization.JsonContainerContract containerContract, Newtonsoft.Json.Serialization.JsonProperty containerProperty) (at C:/Project/Github/Json.Net.Unity3D/src/Newtonsoft.Json/Serialization/JsonSerializerInternalWriter.cs:334)
Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.CalculatePropertyValues (Newtonsoft.Json.JsonWriter writer, System.Object value, Newtonsoft.Json.Serialization.JsonContainerContract contract, Newtonsoft.Json.Serialization.JsonProperty member, Newtonsoft.Json.Serialization.JsonProperty property, Newtonsoft.Json.Serialization.JsonContract& memberContract, System.Object& memberValue) (at C:/Project/Github/Json.Net.Unity3D/src/Newtonsoft.Json/Serialization/JsonSerializerInternalWriter.cs:551)
Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeObject (Newtonsoft.Json.JsonWriter writer, System.Object value, Newtonsoft.Json.Serialization.JsonObjectContract contract, Newtonsoft.Json.Serialization.JsonProperty member, Newtonsoft.Json.Serialization.JsonContainerContract collectionContract, Newtonsoft.Json.Serialization.JsonProperty containerProperty) (at C:/Project/Github/Json.Net.Unity3D/src/Newtonsoft.Json/Serialization/JsonSerializerInternalWriter.cs:485)
Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue (Newtonsoft.Json.JsonWriter writer, System.Object value, Newtonsoft.Json.Serialization.JsonContract valueContract, Newtonsoft.Json.Serialization.JsonProperty member, Newtonsoft.Json.Serialization.JsonContainerContract containerContract, Newtonsoft.Json.Serialization.JsonProperty containerProperty) (at C:/Project/Github/Json.Net.Unity3D/src/Newtonsoft.Json/Serialization/JsonSerializerInternalWriter.cs:173)
Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeObject (Newtonsoft.Json.JsonWriter writer, System.Object value, Newtonsoft.Json.Serialization.JsonObjectContract contract, Newtonsoft.Json.Serialization.JsonProperty member, Newtonsoft.Json.Serialization.JsonContainerContract collectionContract, Newtonsoft.Json.Serialization.JsonProperty containerProperty) (at C:/Project/Github/Json.Net.Unity3D/src/Newtonsoft.Json/Serialization/JsonSerializerInternalWriter.cs:485)
Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue (Newtonsoft.Json.JsonWriter writer, System.Object value, Newtonsoft.Json.Serialization.JsonContract valueContract, Newtonsoft.Json.Serialization.JsonProperty member, Newtonsoft.Json.Serialization.JsonContainerContract containerContract, Newtonsoft.Json.Serialization.JsonProperty containerProperty) (at C:/Project/Github/Json.Net.Unity3D/src/Newtonsoft.Json/Serialization/JsonSerializerInternalWriter.cs:173)
Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeObject (Newtonsoft.Json.JsonWriter writer, System.Object value, Newtonsoft.Json.Serialization.JsonObjectContract contract, Newtonsoft.Json.Serialization.JsonProperty member, Newtonsoft.Json.Serialization.JsonContainerContract collectionContract, Newtonsoft.Json.Serialization.JsonProperty containerProperty) (at C:/Project/Github/Json.Net.Unity3D/src/Newtonsoft.Json/Serialization/JsonSerializerInternalWriter.cs:485)
Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue (Newtonsoft.Json.JsonWriter writer, System.Object value, Newtonsoft.Json.Serialization.JsonContract valueContract, Newtonsoft.Json.Serialization.JsonProperty member, Newtonsoft.Json.Serialization.JsonContainerContract containerContract, Newtonsoft.Json.Serialization.JsonProperty containerProperty) (at C:/Project/Github/Json.Net.Unity3D/src/Newtonsoft.Json/Serialization/JsonSerializerInternalWriter.cs:173)
Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeObject (Newtonsoft.Json.JsonWriter writer, System.Object value, Newtonsoft.Json.Serialization.JsonObjectContract contract, Newtonsoft.Json.Serialization.JsonProperty member, Newtonsoft.Json.Serialization.JsonContainerContract collectionContract, Newtonsoft.Json.Serialization.JsonProperty containerProperty) (at C:/Project/Github/Json.Net.Unity3D/src/Newtonsoft.Json/Serialization/JsonSerializerInternalWriter.cs:485)
Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue (Newtonsoft.Json.JsonWriter writer, System.Object value, Newtonsoft.Json.Serialization.JsonContract valueContract, Newtonsoft.Json.Serialization.JsonProperty member, Newtonsoft.Json.Serialization.JsonContainerContract containerContract, Newtonsoft.Json.Serialization.JsonProperty containerProperty) (at C:/Project/Github/Json.Net.Unity3D/src/Newtonsoft.Json/Serialization/JsonSerializerInternalWriter.cs:173)
Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeObject (Newtonsoft.Json.JsonWriter writer, System.Object value, Newtonsoft.Json.Serialization.JsonObjectContract contract, Newtonsoft.Json.Serialization.JsonProperty member, Newtonsoft.Json.Serialization.JsonContainerContract collectionContract, Newtonsoft.Json.Serialization.JsonProperty containerProperty) (at C:/Project/Github/Json.Net.Unity3D/src/Newtonsoft.Json/Serialization/JsonSerializerInternalWriter.cs:485)
Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue (Newtonsoft.Json.JsonWriter writer, System.Object value, Newtonsoft.Json.Serialization.JsonContract valueContract, Newtonsoft.Json.Serialization.JsonProperty member, Newtonsoft.Json.Serialization.JsonContainerContract containerContract, Newtonsoft.Json.Serialization.JsonProperty containerProperty) (at C:/Project/Github/Json.Net.Unity3D/src/Newtonsoft.Json/Serialization/JsonSerializerInternalWriter.cs:173)
Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeObject (Newtonsoft.Json.JsonWriter writer, System.Object value, Newtonsoft.Json.Serialization.JsonObjectContract contract, Newtonsoft.Json.Serialization.JsonProperty member, Newtonsoft.Json.Serialization.JsonContainerContract collectionContract, Newtonsoft.Json.Serialization.JsonProperty containerProperty) (at C:/Project/Github/Json.Net.Unity3D/src/Newtonsoft.Json/Serialization/JsonSerializerInternalWriter.cs:485)
Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue (Newtonsoft.Json.JsonWriter writer, System.Object value, Newtonsoft.Json.Serialization.JsonContract valueContract, Newtonsoft.Json.Serialization.JsonProperty member, Newtonsoft.Json.Serialization.JsonContainerContract containerContract, Newtonsoft.Json.Serialization.JsonProperty containerProperty) (at C:/Project/Github/Json.Net.Unity3D/src/Newtonsoft.Json/Serialization/JsonSerializerInternalWriter.cs:173)
Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeList (Newtonsoft.Json.JsonWriter writer, System.Collections.IEnumerable values, Newtonsoft.Json.Serialization.JsonArrayContract contract, Newtonsoft.Json.Serialization.JsonProperty member, Newtonsoft.Json.Serialization.JsonContainerContract collectionContract, Newtonsoft.Json.Serialization.JsonProperty containerProperty) (at C:/Project/Github/Json.Net.Unity3D/src/Newtonsoft.Json/Serialization/JsonSerializerInternalWriter.cs:710)
Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue (Newtonsoft.Json.JsonWriter writer, System.Object value, Newtonsoft.Json.Serialization.JsonContract valueContract, Newtonsoft.Json.Serialization.JsonProperty member, Newtonsoft.Json.Serialization.JsonContainerContract containerContract, Newtonsoft.Json.Serialization.JsonProperty containerProperty) (at C:/Project/Github/Json.Net.Unity3D/src/Newtonsoft.Json/Serialization/JsonSerializerInternalWriter.cs:179)
Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.Serialize (Newtonsoft.Json.JsonWriter jsonWriter, System.Object value, System.Type objectType) (at C:/Project/Github/Json.Net.Unity3D/src/Newtonsoft.Json/Serialization/JsonSerializerInternalWriter.cs:95)
Newtonsoft.Json.JsonSerializer.SerializeInternal (Newtonsoft.Json.JsonWriter jsonWriter, System.Object value, System.Type objectType) (at C:/Project/Github/Json.Net.Unity3D/src/Newtonsoft.Json/JsonSerializer.cs:1056)
Newtonsoft.Json.JsonSerializer.Serialize (Newtonsoft.Json.JsonWriter jsonWriter, System.Object value, System.Type objectType) (at C:/Project/Github/Json.Net.Unity3D/src/Newtonsoft.Json/JsonSerializer.cs:967)
Newtonsoft.Json.JsonConvert.SerializeObjectInternal (System.Object value, System.Type type, Newtonsoft.Json.JsonSerializer jsonSerializer) (at C:/Project/Github/Json.Net.Unity3D/src/Newtonsoft.Json/JsonConvert.cs:660)
Newtonsoft.Json.JsonConvert.SerializeObject (System.Object value, System.Type type, Newtonsoft.Json.JsonSerializerSettings settings) (at C:/Project/Github/Json.Net.Unity3D/src/Newtonsoft.Json/JsonConvert.cs:611)
Newtonsoft.Json.JsonConvert.SerializeObject (System.Object value) (at C:/Project/Github/Json.Net.Unity3D/src/Newtonsoft.Json/JsonConvert.cs:532)
SvgMapper.ToJson (System.String svgPath) (at Assets/PPTools/SvgUtils/SvgMapper.cs:107)
ZipLoader+UnZipEvent.OnFinished (System.Boolean _result) (at Assets/Custom/Scripts/Marketing/ZipLoader.cs:62)
ZipWrapper.UnzipFile (System.IO.Stream _inputStream, System.String _outputPath, System.String _password, ZipWrapper+UnzipCallback _unzipCallback) (at Assets/PPTools/SharpZip/ZipWrapper.cs:252)
ZipWrapper.UnzipFile (System.Byte[] _fileBytes, System.String _outputPath, System.String _password, ZipWrapper+UnzipCallback _unzipCallback) (at Assets/PPTools/SharpZip/ZipWrapper.cs:162)
ZipLoader+d__16.MoveNext () (at Assets/Custom/Scripts/Marketing/ZipLoader.cs:160)
UnityEngine.SetupCoroutine.InvokeMoveNext (System.Collections.IEnumerator enumerator, System.IntPtr returnValueAddress) (at C:/buildslave/unity/build/Runtime/Export/Coroutines.cs:17)
how to Ignore reference loop handling.
In Unity 2018 .Net 4.x will be stable (I am currently using the beta)
This means UnityEngine.Keyframe.tangentMode
will be obsolete. We should switch to AnimationUtility.SetLeftTangentMode
, AnimationUtility.SetRightTangentMode
, AnimationUtility.GetLeftTangentMode
or AnimationUtility.GetRightTangentMode
instead.
Hi, I'm having trouble parsing an array. The object is recognized as key - "sculptures", but the array is recognized as type string. Nothing I try will get around this. The object looks like this:
{"sculptures": "[{"fields": {"id": 1, "viewable": true, "date_added": "2015-10-27T18:35:30Z"}, "model": "server.sculpture", "pk": 1}]"}
This json has been validated with jsonlint
Hello, this is more of a question than anything else: What platforms does this library support, and if there are any limitations when working on certain platforms?
Thank you.
The following characters are not decoded when appearing in a string in the passed JSON:
æ
- encoded as \u00e6
ø
- encoded as \u00f8
(More to come😊)
I am using JSONObject with Unity to build an iOS app. I need to parse a large JSON object (around 100KB).
It works perfectly when using the Mono Backend but when I switch to IL2CPP to support arm64, the app gets stuck parsing the JSON object. This is a profile of the app when it has started parsing the object:
I can see most of the time is spent in allocations and string comparisons.
Any suggestion on how to fix this?
When Type.NUMBER is converted to string during Stringify
, both versions, Type.NUMBER isn't converted to string using InvariantCulture, meaning cultures that use comma for decimal points can get errors converting later on.
This:
case Type.NUMBER:
if(useInt) {
builder.Append(i.ToString());
} else {
#if USEFLOAT
if(float.IsInfinity(n))
builder.Append(INFINITY);
else if(float.IsNegativeInfinity(n))
builder.Append(NEGINFINITY);
else if(float.IsNaN(n))
builder.Append(NaN);
#else
if(double.IsInfinity(n))
builder.Append(INFINITY);
else if(double.IsNegativeInfinity(n))
builder.Append(NEGINFINITY);
else if(double.IsNaN(n))
builder.Append(NaN);
#endif
else
builder.Append(n.ToString());
}
break;
Should be:
case Type.NUMBER:
if(useInt) {
builder.Append(i.ToString());
} else {
#if USEFLOAT
if(float.IsInfinity(n))
builder.Append(INFINITY);
else if(float.IsNegativeInfinity(n))
builder.Append(NEGINFINITY);
else if(float.IsNaN(n))
builder.Append(NaN);
#else
if(double.IsInfinity(n))
builder.Append(INFINITY);
else if(double.IsNegativeInfinity(n))
builder.Append(NEGINFINITY);
else if(double.IsNaN(n))
builder.Append(NaN);
#endif
else
builder.Append(n.ToString(CultureInfo.InvariantCulture));
}
break;
string json = "{\"position\": [1.312, 4.606373506565475, -2.005028074709216]}";
JSONObject obj = new JSONObject(json);
Debug.Log(obj.GetField("position")[0]);
outputs 1312
.
This is a localization bug, because in Germany we use "," instead of "." as separation:
Debug.Log(System.Convert.ToSingle("1,123")); // Outputs 1,123
Debug.Log(System.Convert.ToSingle("1.123")); // Outputs 1123
Thank you for putting this out there, it's been very useful to me!
Could you please clarify what's the license of this? Any chance you could make it MIT?
JSONObject array=new JSONObject("[]");
Debug.Log(array.list);
Output : Null
JSONObject array=new JSONObject("[ ]"); // whitespace between square bracket
Debug.Log(array.list);
Output : System.Collections.Generic.List`1[Defective.JSON.JSONObject]
Its return List with count 1
I'm using JSON with quoted strings, e.g.
"key": "value"
And all my values are, when I use ToString() not value, but "value" - with quotes retained. So I have to add .Trim('"') to all the requests and started to wonder if that isn't a bug.
Thanks for this library. One thing that surprises me is that it uses float by default and only offers doubles if you comment out the USEFLOAT directive (and if you do, you get a compiler error). We're using it to transfer geospatial data, and if I cast the latitudes and longitudes to floats, there is a significant rounding error.
Why is float the default anyways? IMHO, doubles would work better, since JavaScript numbers are doubles anyways and thus this seems to be a better match to JSON.
If there is a specific reason as to why to use floats, I would strongly recommend to at least support doubles by additional constructors / Add() methods.
Since I did not want to patch the library itself, I am now converting the doubles to strings, transfer them as such, and re-parse them to JavaScript numbers on the server-side. Which is a pretty weird workaround.
I need parse large JSON ( ~ 2mb ) in unity . But when use this code :
JSONObject dataObj = new JSONObject (_data);
game paused like Time.timeScale = 0 about 25s (Only sound play).
I need make a loadingbar while it parsing data .How to do that ?
We had a problem that certain strings were downloaded as unescaped strings and gave us back text where the ' was displayed as \n27 and " as " .
W fixed it by changing the lines
obj.str = val;
to
obj.str = Regex.Unescape(val);
This would be great to either have ist be enabled as an option or as a default as I don't think many want unescaped strings.
Thanks for the work you do :)
Assets\JSON\JSONObject.cs(250,8): error CS1502: �롰string.Compare(string, string, System.StringComparison)����ƥ�������ط�������һЩ��Ч����
Assets\JSON\JSONObject.cs(250,36): error CS1503: ���� 3: ���ӡ�bool��ת��Ϊ��System.StringComparison��
....
When the platform is " Windows Store " , the project can't build .
JSONObject Data = new JSONObject(JSONObject.Type.Object);
Data.AddField("id",1);
Data.AddField("request_id",null);
Debug.Log("data:"+Data.ToString());
not log data and error !!!
I have noticed that pooling has some issues with NULL references in releaseQueue. I was able to reproduce this problem almost every time when parsing larger json.
The issue is that adding the reference back to releaseQueue in object destructor is NOT enough. GC might not recheck references anymore and that is the reason why pooled objects are lost in releaseQueue (GCed).
You have to tell explicitly to GC that you messed with reference of a object that is about to get removed completely by calling System.GC.ReRegisterForFinalize(obj);
This might cause destructor to run twice so you have to add a flag indicating that object was already added to pool private bool isPooled;
Set this variable to true when object is Queued and to false when Dequeued.
NOTE: I also added lock just because I am parsing on concurrent threads.
private bool isPooled = false;
public static JSONObject Create() {
#if POOLING
JSONObject result = null;
lock (releaseQueue)
{
while (result == null && releaseQueue.Count > 0)
{
result = releaseQueue.Dequeue();
#if DEV
//The following cases should NEVER HAPPEN (but they do...)
if(result == null)
Debug.WriteLine("wtf " + releaseQueue.Count);
else if(result.list != null)
Debug.WriteLine ("wtflist " + result.list.Count);
#endif
}
}
if (result != null)
{
result.isPooled = false;
return result;
}
#endif
return new JSONObject();
}
~JSONObject() {
if(pool && !isPooled && releaseQueue.Count < MAX_POOL_SIZE) {
type = Type.NULL;
list = null;
keys = null;
str = "";
n = 0;
b = false;
isPooled = true;
lock (releaseQueue)
{
releaseQueue.Enqueue(this);
}
System.GC.ReRegisterForFinalize(this);
}
}
After applying these changes I have not encountered "wtf/wtflist" log messages anymore caused by NULL dequeued from releaseQueue.
{
"Version": 21,
"BaseTime": "2017-1-1T0.000000:0.000000:0.000000z type: 1",
"BaseTimeSec": 0.000000,
"range": {
"Name": "xxxxDelta1123",
"minTime": -20940600.000000,
"maxTime": -20917800.000000,
}
}
xxxxDelta1123 will fail to parse because your code only allows values to be numbers when inside a {}
Hi,
I am working with the Universal Windows Platform (UWP) for .Net 4.6 inside the Unity 3D Engine and I like to use JSONObject. It works, but when I access for example a string using ".str":
using (DataReader reader = args.GetDataReader()) {
reader.UnicodeEncoding = UnicodeEncoding.Utf8;
string read = reader.ReadString(reader.UnconsumedBufferLength); // e.g. "{\"msg\":\"connected\",\"session\":\"Rgpudsgk7ZXfBuyGo\"}";
JSONObject obj = new JSONObject(read);
string msg = obj["msg"].str;
}
I get this error message:
Exception thrown: 'System.NullReferenceException' in Assembly-CSharp.dll
Unhandled 'Platform.NullReferenceException' exception caught! - 'Invalid pointer
Object reference not set to an instance of an object.', Sender: '<null>'. Missing try/catch blocks.
(Filename: C:\buildslave\unity\build\PlatformDependent/MetroPlayer/MetroDebug.cpp Line: 46)
but I can still Log msg:
Debug.Log(msg); // logged as 'connected' (WITHOUT single quotes)
So there is not really something wrong.
When the string is set directly and not comming from the MessageWebSocket I don't get the error, same if I accessing .str and logging the output directly - that does not create the error message either, so I assume it is not an error in the JSON-parsing code:
Debug.Log(obj["msg"]); // logged as "connected" (with quotes)
I like to get rid of this error, but I don't know how because I do not get any stacktrace where the exact error is. I don't have this problem when I run the code inside the Unity Editor.
I am compiling this as "Debug" from Visual Studio and checked "Unity C# Project" as well as "Development Build" when building from the Unity Debugger.
Does anybody have a fix or some idea how to get to the error?
Hey Matt,
I love this project and am using it in my own work with Unity. Thanks so much for all your hard work on it!
Just wanted to mention that the JSONChecker is a bit misleading in that there are lots of malformed (invalid JSON) strings that return success in the checker, giving the quick impression that they are valid JSON. I know the screen at the bottom shows the output, but it still confused me for a while. It looks like the checker is checking whether JSONObject was able to parse the string at all, not whether the string is valid JSON. And it seems that the parser succeeds at making sense of lots of junky strings, although the returned data is pretty much always different.
To address this, maybe add a bit of clarifying language to the success message? It might also be worth a bit of extra language in the readme making it clear that the parser sometimes quietly accepts invalid JSON.
This all came about because I was looking for a way to validate JSON input in the Unity inspector, so I was looking for a built-in method in JSONObject to do that. I know adding a JSON validator is not probably something you want to do, but I just wanted to mention this issue since it might come up for others.
Thanks again for a great project!
On different machines numbers are being converted in different formats.
the number 26.643470764160158 (using float conversion), on my machine is serialized as 26.64347
but on another machine it was serialized as 2.6xxxE+16. This wouldnt be a problem but when converting back, it ingores the notation, returning 2.6xxx.
To fix this i needed to use
System.Globalization.CultureInfo.DefaultThreadCurrentCulture = System.Globalization.CultureInfo.InvariantCulture;
System.Globalization.CultureInfo.DefaultThreadCurrentUICulture** = System.Globalization.CultureInfo.InvariantCulture;
You can add this on JSONObject class, or on each method of System.Convert, call for CultureInfo.InvariantCulture as the second parameter.
Sorry for the rushed post, I'm in a hurry on my project, but wanted to at least let you guys know.
Regards
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.