Giter VIP home page Giter VIP logo

litjson's Introduction

LitJSON

NuGet MyGet

A .Net library to handle conversions from and to JSON (JavaScript Object Notation) strings.

It's quick and lean, without external dependencies. Just a few classes so easily embeddable in your own code or a very small assembly to ship with your code. The code is highly portable, which in general makes it easy to adapt for new platforms.

Continuous integration

Build server Platform Build status
AppVeyor Windows AppVeyor branch
Bitrise MacOS Build Status
Bitrise Linux Build Status
Azure Pipelines Linux / MacOS / Windows Azure Pipelines Build Status
GitHub Actions Linux / MacOS / Windows Build

Compiling

Code can be compiled using .NET CLI or by launching the bootstrappers in the root of the repository.

Windows

./build.ps1

Linux / OS X

./build.sh

Prerequisites

The bootstrappers will (locally in repo)

  • Fetch and install .NET Core CLI / SDK version needed to compile LitJSON.
  • Fetch and install Cake runner
  • Execute build script with supplied target (--target=[Target]) or by default
    1. Clean previous artifacts
    2. Restore build dependencies from NuGet
    3. Build
    4. Run unit tests
    5. Create NuGet package

Testing

This library comes with a set of unit tests using the NUnit framework.

Using LitJSON from an application

Package manager

Install-Package LitJson -Version 0.19.0

.NET CLI

dotnet add package LitJson --version 0.19.0

Paket CLI

paket add LitJson --version 0.19.0

Alternatively, just copy the whole tree of files under src/LitJSON to your own project's source tree and integrate it with your development environment.

Requirements

LitJSON currently targets and supports

  • .NET 8
  • .NET 6
  • .NET Standard 2.1
  • .NET Standard 2.0
  • .NET Standard 1.5
  • .NET Framework 4.8
  • .NET Framework 4.5
  • .NET Framework 4.0
  • .NET Framework 3.5 (including SQLCLR, for which WCOMAB/SqlServerSlackAPI is an example of)
  • .NET Framework 2.0
  • Mono 4.4.2 and above

Prereleases

Each merge to develop is published to our NuGet feed on MyGet and also GitHub Packages.

Contributing

So you’re thinking about contributing to LitJSON? Great! It’s really appreciated.

  • Create an issue
  • Fork the repository.
  • Create a feature branch from develop to work in.
  • Make your feature addition or bug fix.
  • Don't forget the unit tests.
  • Send a pull request.

License

Unlicense (public domain).

litjson's People

Contributors

blubbfish avatar devlead avatar grantfar avatar hogiyogi597 avatar ikasoumen4 avatar immitev avatar kdw9502 avatar lbv avatar michaelbartnett avatar mickeykim avatar summitn avatar udlose avatar whoo24 avatar zhenlinyang avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

litjson's Issues

unable to map json to a child class

hello! i have an abstract Class that is extended by a childClass.
When i run

childClass c = JsonMapper.ToObject<childClass>(json);

my childClass contains default value and not the one contained in json.

if i remove abstract from Class and use

Class c = JsonMapper.ToObject<Class>(json);

everything works fine.

so the problem should be related to inheritance.

thank you.

Downgrade detected for System.Reflection.TypeExtensions.

I think current version of System.Reflection.TypeExtensions in your library is 4.1.0 and my project already has one library that has uses TypeExtensions with version >=4.3.0. So, it is giving me this error ...

Severity	Code	Description	Project	File	Line	Suppression State
Error	NU1605	Detected package downgrade: System.Reflection.TypeExtensions from 4.3.0 to 4.1.0. Reference the package directly from the project to select a different version. 
 ScClient.Unity -> LitJson 0.13.0 -> NETStandard.Library 1.6.1 -> System.Linq.Expressions 4.3.0 -> System.Reflection.TypeExtensions (>= 4.3.0) 
 ScClient.Unity -> LitJson 0.13.0 -> System.Reflection.TypeExtensions (>= 4.1.0)	ScClient	C:\Users\SAC\RiderProjects\ScClient.Unity\ScClient\ScClient.csproj	1	

Decode the JsonData to Object

Hi. I have some troubles with flow of parsing.
First of all i have long json (response from server) and I need check this response on few keys.

Example
{"account":{"id":"00000000001", "name": "NewUser"},"buildings":[{"id":"b000000001", "typeId":1}]}

And I wanna get data by keys and convert these values to my models of data. Accordingly to this I have model for account(Account.cs) and model for buildings(list of Building.cs).

My flow:
I convert json(string) to the JsonData
JsonData jData = JsonMapper.ToObject<T>(jsonString);

after this I check all keys of inst_object, and get the value of account or buildings

T response = default(T);
foreach(KeyValuePair pair in inst_object)
{
  if (pair.Key == key)
  {
    if (pair.Value != null && pair.Value.GetJsonType() != JsonType.None)
    {
      response = Decode(pair.Value);
    }
    break;
  }
}

last step this convert JsonData to json and doubleconvert to the object

public static T Decode<T>(JsonData data)
    {
        if (data != null && data.GetJsonType() != JsonType.None)
        {
            string jsonString = JsonMapper.ToJson(data);
            return JsonMapper.ToObject<T>(jsonString);
        }
        else
        {
            var cResponse = System.Activator.CreateInstance(typeof(T));
            return (T)cResponse;
        }
    }

QUESTION:
Can we convert the part of json to the model of data by standart functionality?

Bug when deserializing double embedded JsonArray

When using JsonMapper.ToObject(targetString) to deserialize a double embedded json array, such as
[ [ "1.5,1.5,1.5", "-1.5,-1.5,1.5" ] ]
it will return a JsonData which gives out "[]" when trying to
print(JsonMapper.ToObject(targetString).ToJson())
If we add an outer parent object, such as
{ "data": [ [ "1.5,1.5,1.5", "-1.5,-1.5,1.5" ] ] }
and we try to get the embedded array using
JsonData jsonData = JsonMapper.ToObject(targetString);
print(jsonData["data"].ToJson());
it will throw "ArgumentException: The key has to be a string" and print the following trace:
LitJson.JsonData.System.Collections.IDictionary.set_Item (System.Object key, System.Object value)
LitJson.JsonMapper.ReadValue (LitJson.WrapperFactory factory, LitJson.JsonReader reader)
LitJson.JsonMapper.ToWrapper (LitJson.WrapperFactory factory, System.String json)
LitJson.JsonMapper.ToObject (System.String json)

It works well with single array situation, hoping you could fix this problem (I believe it is not caused by wrong operation). By the way, I am a Unity programmer, this info might help you.

LitJSON null type and empty array bugs

I use LitJson with Unity3d.
There are two bugs I have found:

  • LitJson doesn't handle null-type:
string jsonStr = "{'body':null}";
LitJson.JsonData jsonData = LitJson.JsonMapper.ToObject(jsonStr);
jsonStr = LitJson.JsonMapper.ToJson(jsonData); //exception here
  • LitJson looses all data in array. If it's the root of JSON:
string jsonStr = "[[],[],[]]";
LitJson.JsonData jsonData = LitJson.JsonMapper.ToObject(jsonStr);
jsonStr = LitJson.JsonMapper.ToJson(jsonData);
Debug.Log(jsonStr); // []

JsonMapper and accents

Hi ! I can't manage to fix this issue, any idea ?

I have this Json =

[{"id":"CS_001","name":"L'élément","type":"Tôt"},{"id":"CS_002","name":"L'outrage","type":"Tôt"},{"id":"CS_003","name":"Test","type":"Tôt"}]

Public class test : MonoBehaviour {
private string jsonString;
private JsonData cardData;
JsonData database;

void Start () {
    jsonString = File.ReadAllText (Application.dataPath + "/test.json");
    cardData = JsonMapper.ToObject (jsonString);
    database = JsonMapper.ToJson (cardData);
    Debug.Log (database.ToString ());
    File.WriteAllText (Application.dataPath + "/carte2.json", database);
}

}

The Debug.Log and the File are = [{"id":"CS_001","name":"L'\u00E9l\u00E9ment","type":"T\u00F4t"},{"id":"CS_002","name":"L'outrage","type":"T\u00F4t"},{"id":"CS_003","name":"Test","type":"T\u00F4t"}]

I would like to keep the accents into the json, is that possible? Thank you

Error on Windows Phone 8

I use litjson on my Unity project, then export Android, IOS and BB10 without any mistakes, but when exporting WP8 an error is reported.

Log:
Error building Player: Exception: Error: method System.Type System.Type::GetInterface(System.String) doesn't exist in target framework. It is referenced from LitJson.dll at System.Void LitJson.JsonMapper::AddArrayMetadata(System.Type).
Error: method System.Type System.Type::GetInterface(System.String) doesn't exist in target framework. It is referenced from LitJson.dll at System.Void LitJson.JsonMapper::AddObjectMetadata(System.Type).

JsonData throws InvalidCastException when casting number to long.

JsonData appears to support both int and long types. However the end-user has difficulty in using the long data type due to a weird InvalidCastExceptions being thrown. When reading in a number that will fit in an int, JsonData sets the type as int. But it should be easy to cast to a long.

For instance:

string json = "{ 'number' : 100 }";
JsonData jObj = JsonMapper.ToObject(json);

int numberAsInt = (int) jObj ["number"];                // works fine
long numberAsLong = (long) jObj ["number"];      // InvalidCastException thrown!

// wordy alternative is...
JsonData numberObj = jObj ["number"]; 
long numberAsLong2 = numberObj.IsLong ? (long) numberObj : (int) numberObj;

Stack trace is as follows:

InvalidCastException: Instance of JsonData doesn't hold an int
LitJson.JsonData.op_Explicit (LitJson.JsonData data)
(etc)

Expected behaviour: it should be easy to use long as a data type without doing weird casts like the above.

A issue

Hey:
Now I hava a problem, now I use litjson to serialize string from remote server, but the server may send some empty string array or null,eg:string[] eg={} or string[] eg=null,and my class do it like this:
public class Eg(){public string[] eg;}
if in this case ,I think my serizalized data shoud be string[] eg=string.empty or string[] eg=null,but it throw error:MissingMethodException: Default constructor not found for type System.String
what should I do for the data? I use litjson for unity develop,thank your for your help

move to .net core!

who can move it to .net core?
It's very important for me.Anyone help?

JsonMapper.ToJson(obj) throws exception if class has a JsonData member

Repro:

// Create some class.
class TestClass {
   public JsonData data = new JsonData();
   public TestClass() { data["foo"] = "bar";  }
}

// Try to map it to json.
TestClass blah = new TestClass();
string json = JsonMapper.ToJson(blah);

This code throws an exception in JsonWriter:
"Can't close an object here"

The problem is that the ExpectingValue flag is not getting cleared when writing nested objects. This flag gets cleared in the Writer functions for writing basic types (e.g. string, int, etc), but the JsonMapper allocates new instances of Writer to write nested JsonData objects.

In my code, I fixed this by adding a function to JsonWriter:
public void ClearExpectingValue() { context.ExpectingValue = false; }

And calling this from JsonMapper at line 707, like this:

        private static void WriteValue (object obj, JsonWriter writer,
                                        bool writer_is_private,
                                        int depth)
        {
            if (depth > max_nesting_depth)
                throw new JsonException (
                    String.Format ("Max allowed object depth reached while " +
                                   "trying to export from type {0}",
                                   obj.GetType ()));

            if (obj == null) {
                writer.Write (null);
                return;
            }

            if (obj is IJsonWrapper) {
                if (writer_is_private)
                    writer.TextWriter.Write (((IJsonWrapper) obj).ToJson ());
                else
                    ((IJsonWrapper) obj).ToJson (writer);

                writer.ClearExpectingValue();

                return;
            }

             // etc.....

build failed

[00:00:00] Build started
[00:00:01] git config --global core.autocrlf input
[00:00:01] git clone -q --branch=develop https://github.com/FollowCD/litjson.git C:\projects\litjson
[00:00:02] git checkout -qf aee3e16
[00:00:02] .\build.ps1 --target="AppVeyor" --verbosity=Verbose
[00:00:04] dotnet-install: Downloading link: https://dotnetcli.azureedge.net/dotnet/Sdk/2.1.4/dotnet-sdk-2.1.4-win-x64.zip
[00:00:05] dotnet-install: Extracting zip from https://dotnetcli.azureedge.net/dotnet/Sdk/2.1.4/dotnet-sdk-2.1.4-win-x64.zip
[00:00:15] dotnet-install: Adding to current process PATH: "C:\projects\litjson.dotnet". Note: This change will not be visible if PowerShell was run as a child process.
[00:00:15] dotnet-install: Installation finished
[00:00:15] Installing Cake 0.25.0...
[00:00:17] Analyzing build script...
[00:00:17] Processing build script...
[00:00:17] Installing tools...
[00:00:23] Compiling build script...
[00:00:28]
[00:00:28] ----------------------------------------
[00:00:28] Setup
[00:00:28] ----------------------------------------
[00:00:28] Executing custom setup action...
[00:00:28] Calculating Semantic Version
[00:00:28] INFO [06/14/18 20:14:56:62] Working directory: C:\projects\litjson
[00:00:28] INFO [06/14/18 20:14:56:63] IsDynamicGitRepository: False
[00:00:28] INFO [06/14/18 20:14:56:81] Returning Project Root from DotGitDirectory: C:\projects\litjson.git - C:\projects\litjson
[00:00:28] INFO [06/14/18 20:14:56:82] Running on Windows.
[00:00:28] INFO [06/14/18 20:14:56:82] Applicable build agent found: 'AppVeyor'.
[00:00:28] INFO [06/14/18 20:14:56:82] Branch from build environment:
[00:00:29] INFO [06/14/18 20:14:57:24] IsDynamicGitRepository: False
[00:00:29] INFO [06/14/18 20:14:57:24] Returning Project Root from DotGitDirectory: C:\projects\litjson.git - C:\projects\litjson
[00:00:29] INFO [06/14/18 20:14:57:24] Project root is: C:\projects\litjson
[00:00:29] INFO [06/14/18 20:14:57:24] DotGit directory is: C:\projects\litjson.git
[00:00:29] INFO [06/14/18 20:14:57:25] IsDynamicGitRepository: False
[00:00:29] INFO [06/14/18 20:14:57:25] Returning Project Root from DotGitDirectory: C:\projects\litjson.git - C:\projects\litjson
[00:00:29] INFO [06/14/18 20:14:57:25] Begin: Loading version variables from disk cache
[00:00:29] INFO [06/14/18 20:14:57:25] Cache file C:\projects\litjson.git\gitversion_cache\BDF4B71F4AAC6B5AA364F281D90020AE5C975CBC.yml not found.
[00:00:29] INFO [06/14/18 20:14:57:25] End: Loading version variables from disk cache (Took: 1.00ms)
[00:00:29] INFO [06/14/18 20:14:57:25] IsDynamicGitRepository: False
[00:00:29] INFO [06/14/18 20:14:57:25] Returning Project Root from DotGitDirectory: C:\projects\litjson.git - C:\projects\litjson
[00:00:29] INFO [06/14/18 20:14:57:35] Using latest commit on specified branch
[00:00:29] INFO [06/14/18 20:14:57:39] Running against branch: develop (aee3e16)
[00:00:29] INFO [06/14/18 20:14:57:41] 0 commits found between aee3e16 and aee3e16
[00:00:29] INFO [06/14/18 20:14:57:41] Begin: Calculating base versions
[00:00:29] INFO [06/14/18 20:14:57:50] Fallback base version: 0.1.0 with commit count source c92aadb
[00:00:29] INFO [06/14/18 20:14:57:61] Git tag 'v0.13.0': 0.13.0 with commit count source aee3e16
[00:00:29] INFO [06/14/18 20:14:57:61] Git tag 'v0.12.0': 0.12.0 with commit count source a9bbc1c
[00:00:29] INFO [06/14/18 20:14:57:62] Git tag 'v0.9.0': 0.9.0 with commit count source e16713d
[00:00:29] INFO [06/14/18 20:14:57:62] Git tag 'v0.7.0': 0.7.0 with commit count source 7b389ec
[00:00:29] INFO [06/14/18 20:14:57:67] Merge target tagged 'v0.13.0': 0.13.0 with commit count source aee3e16
[00:00:29] INFO [06/14/18 20:14:57:67] Merge target tagged 'v0.12.0': 0.12.0 with commit count source a9bbc1c
[00:00:29] INFO [06/14/18 20:14:57:67] Merge target tagged 'v0.11.0': 0.11.0 with commit count source 52d96c7
[00:00:29] INFO [06/14/18 20:14:57:67] Merge target tagged 'v0.10.0': 0.10.0 with commit count source 0f970e2
[00:00:29] INFO [06/14/18 20:14:57:67] Merge target tagged 'v0.10.0': 0.10.0 with commit count source 0f970e2
[00:00:29] INFO [06/14/18 20:14:57:67] Merge target tagged 'v0.9.0': 0.9.0 with commit count source e16713d
[00:00:29] INFO [06/14/18 20:14:57:68] Merge target tagged 'v0.7.0': 0.7.0 with commit count source 7b389ec
[00:00:29] INFO [06/14/18 20:14:57:74] Merge message 'Merge branch 'release/0.11.0' into develop
[00:00:29]
[00:00:29] * release/0.11.0:
[00:00:29] Release notes migrated to litjson.net': 0.11.0 with commit count source c6af2aa
[00:00:29] INFO [06/14/18 20:14:57:75] Found multiple base versions which will produce the same SemVer (0.13.0), taking oldest source for commit counting (Git tag 'v0.12.0')
[00:00:29] INFO [06/14/18 20:14:57:75] Base version used: Merge target tagged 'v0.12.0': 0.12.0 with commit count source a9bbc1c
[00:00:29] INFO [06/14/18 20:14:57:75] End: Calculating base versions (Took: 338.01ms)
[00:00:29] INFO [06/14/18 20:14:57:79] 6 commits found between a9bbc1c and aee3e16
[00:00:29] INFO [06/14/18 20:14:57:80] Begin: Creating dictionary
[00:00:29] INFO [06/14/18 20:14:57:80] End: Creating dictionary (Took: 2.00ms)
[00:00:29] INFO [06/14/18 20:14:57:80] Begin: Storing version variables to cache file C:\projects\litjson.git\gitversion_cache\BDF4B71F4AAC6B5AA364F281D90020AE5C975CBC.yml
[00:00:29] INFO [06/14/18 20:14:57:84] End: Storing version variables to cache file C:\projects\litjson.git\gitversion_cache\BDF4B71F4AAC6B5AA364F281D90020AE5C975CBC.yml (Took: 39.00ms)
[00:00:29] INFO [06/14/18 20:14:57:84] Applicable build agent found: 'AppVeyor'.
[00:00:29] Executing GenerateSetVersionMessage for 'AppVeyor'.
[00:00:30] Set AppVeyor build number to '0.13.0'.
[00:00:30] Executing GenerateBuildLogOutput for 'AppVeyor'.
[00:00:30] Adding Environment Variable. name='GitVersion_Major' value='0']
[00:00:30] Adding Environment Variable. name='GitVersion_Minor' value='13']
[00:00:30] Adding Environment Variable. name='GitVersion_Patch' value='0']
[00:00:30] Adding Environment Variable. name='GitVersion_PreReleaseTag' value='']
[00:00:30] Adding Environment Variable. name='GitVersion_PreReleaseTagWithDash' value='']
[00:00:30] Adding Environment Variable. name='GitVersion_PreReleaseLabel' value='']
[00:00:30] Adding Environment Variable. name='GitVersion_PreReleaseNumber' value='']
[00:00:30] Adding Environment Variable. name='GitVersion_BuildMetaData' value='']
[00:00:30] Adding Environment Variable. name='GitVersion_BuildMetaDataPadded' value='']
[00:00:30] Adding Environment Variable. name='GitVersion_FullBuildMetaData' value='Branch.develop.Sha.aee3e16648554cc011e2526ec3c0ca5de094a736']
[00:00:30] Adding Environment Variable. name='GitVersion_MajorMinorPatch' value='0.13.0']
[00:00:30] Adding Environment Variable. name='GitVersion_SemVer' value='0.13.0']
[00:00:30] Adding Environment Variable. name='GitVersion_LegacySemVer' value='0.13.0']
[00:00:30] Adding Environment Variable. name='GitVersion_LegacySemVerPadded' value='0.13.0']
[00:00:30] Adding Environment Variable. name='GitVersion_AssemblySemVer' value='0.13.0.0']
[00:00:30] Adding Environment Variable. name='GitVersion_FullSemVer' value='0.13.0']
[00:00:30] Adding Environment Variable. name='GitVersion_InformationalVersion' value='0.13.0+Branch.develop.Sha.aee3e16648554cc011e2526ec3c0ca5de094a736']
[00:00:30] Adding Environment Variable. name='GitVersion_BranchName' value='develop']
[00:00:30] Adding Environment Variable. name='GitVersion_Sha' value='aee3e16648554cc011e2526ec3c0ca5de094a736']
[00:00:30] Adding Environment Variable. name='GitVersion_NuGetVersionV2' value='0.13.0']
[00:00:30] Adding Environment Variable. name='GitVersion_NuGetVersion' value='0.13.0']
[00:00:30] Adding Environment Variable. name='GitVersion_CommitsSinceVersionSource' value='6']
[00:00:30] Adding Environment Variable. name='GitVersion_CommitsSinceVersionSourcePadded' value='0006']
[00:00:30] Adding Environment Variable. name='GitVersion_CommitDate' value='2018-05-09']
[00:00:30] Copying file AssemblyInfo.cs.in to C:/projects/litjson/src/LitJson/AssemblyInfo.cs
[00:00:31] Calculated Semantic Version: 0.13.0
[00:00:31] Running tasks...
[00:00:31]
[00:00:31] ========================================
[00:00:31] Clean
[00:00:31] ========================================
[00:00:31] Executing task: Clean
[00:00:31] Creating directory C:/projects/litjson/src/bin
[00:00:31] Creating directory C:/projects/litjson/test/bin
[00:00:31] Creating directory C:/projects/litjson/src/obj
[00:00:31] Creating directory C:/projects/litjson/test/obj
[00:00:31] Creating directory C:/projects/litjson/artifacts/nuget
[00:00:31] Finished executing task: Clean
[00:00:31]
[00:00:31] ========================================
[00:00:31] Restore
[00:00:31] ========================================
[00:00:31] Executing task: Restore
[00:00:35] Restoring packages for C:\projects\litjson\src\LitJson\LitJSON.csproj...
[00:00:35] Restoring packages for C:\projects\litjson\test\LitJSON.Tests.csproj...
[00:00:36] Installing SourceLink.Create.GitHub 2.8.1.
[00:00:38] Installing System.Diagnostics.TextWriterTraceListener 4.0.0.
[00:00:38] Installing System.ComponentModel.EventBasedAsync 4.0.11.
[00:00:38] Installing Microsoft.DotNet.PlatformAbstractions 1.0.3.
[00:00:38] Installing Microsoft.TestPlatform.ObjectModel 15.5.0.
[00:00:38] Installing Microsoft.Extensions.DependencyModel 1.0.3.
[00:00:38] Installing System.Xml.XPath.XmlDocument 4.3.0.
[00:00:38] Installing System.ComponentModel.EventBasedAsync 4.3.0.
[00:00:38] Installing Microsoft.TestPlatform.TestHost 15.5.0.
[00:00:38] Installing Microsoft.CodeCoverage 1.0.3.
[00:00:38] Installing Microsoft.NET.Test.Sdk 15.5.0.
[00:00:38] Installing NUnit 3.9.0.
[00:00:38] Installing NUnit3TestAdapter 3.9.0.
[00:00:39] Generating MSBuild file C:\projects\litjson\src\LitJson\obj\LitJSON.csproj.nuget.g.props.
[00:00:39] Generating MSBuild file C:\projects\litjson\src\LitJson\obj\LitJSON.csproj.nuget.g.targets.
[00:00:39] Restore completed in 4.33 sec for C:\projects\litjson\src\LitJson\LitJSON.csproj.
[00:00:39] Restoring packages for C:\projects\litjson\src\LitJson\LitJSON.csproj...
[00:00:40] Installing LibGit2Sharp.NativeBinaries 1.0.165.
[00:00:40] Installing LibGit2Sharp.Portable 0.24.10.
[00:00:40] Installing Newtonsoft.Json 10.0.3.
[00:00:40] Installing Microsoft.Extensions.CommandLineUtils 1.1.1.
[00:00:40] Installing dotnet-sourcelink-git 2.8.1.
[00:00:41] Generating MSBuild file C:\projects\litjson\test\obj\LitJSON.Tests.csproj.nuget.g.props.
[00:00:41] Generating MSBuild file C:\projects\litjson\test\obj\LitJSON.Tests.csproj.nuget.g.targets.
[00:00:41] Restore completed in 5.69 sec for C:\projects\litjson\test\LitJSON.Tests.csproj.
[00:00:41] Restoring packages for C:\projects\litjson\src\LitJson\LitJSON.csproj...
[00:00:41] Installing NuGet.Versioning 4.4.0.
[00:00:41] Installing NuGet.Frameworks 4.4.0.
[00:00:41] Installing NuGet.Packaging.Core 4.4.0.
[00:00:41] Installing NuGet.Common 4.4.0.
[00:00:41] Installing NuGet.Packaging 4.4.0.
[00:00:41] Installing dotnet-sourcelink 2.8.1.
[00:00:42] Restore completed in 2.69 sec for C:\projects\litjson\src\LitJson\LitJSON.csproj.
[00:00:42] Restore completed in 1.65 sec for C:\projects\litjson\src\LitJson\LitJSON.csproj.
[00:00:42] Finished executing task: Restore
[00:00:42]
[00:00:42] ========================================
[00:00:42] Build
[00:00:42] ========================================
[00:00:42] Executing task: Build
[00:00:43] Microsoft (R) Build Engine version 15.7.179.6572 for .NET Core
[00:00:43] Copyright (C) Microsoft Corporation. All rights reserved.
[00:00:43]
[00:00:53] LitJSON -> C:\projects\litjson\src\LitJson\bin\Release\net45\LitJSON.dll
[00:00:53] LitJSON -> C:\projects\litjson\src\LitJson\bin\Release\netstandard2.0\LitJSON.dll
[00:00:55] LitJSON -> C:\projects\litjson\src\LitJson\bin\Release\net40\LitJSON.dll
[00:00:55] LitJSON -> C:\projects\litjson\src\LitJson\bin\Release\netstandard1.5\LitJSON.dll
[00:00:56] LitJSON -> C:\projects\litjson\src\LitJson\bin\Release\net35\LitJSON.dll
[00:00:56] LitJSON.Tests -> C:\projects\litjson\test\bin\Release\net45\LitJSON.Tests.dll
[00:00:57] LitJSON.Tests -> C:\projects\litjson\test\bin\Release\netcoreapp2.0\LitJSON.Tests.dll
[00:00:58] LitJSON -> C:\projects\litjson\src\LitJson\bin\Release\net20\LitJSON.dll
[00:00:58]
[00:00:58] Build succeeded.
[00:00:58] 0 Warning(s)
[00:00:58] 0 Error(s)
[00:00:58]
[00:00:58] Time Elapsed 00:00:14.90
[00:00:58] Finished executing task: Build
[00:00:58]
[00:00:58] ========================================
[00:00:58] Test
[00:00:58] ========================================
[00:00:58] Executing task: Test
[00:00:58] Test run for C:\projects\litjson\test\bin\Release\netcoreapp2.0\LitJSON.Tests.dll(.NETCoreApp,Version=v2.0)
[00:00:58] Microsoft (R) Test Execution Command Line Tool Version 15.7.0
[00:00:58] Copyright (c) Microsoft Corporation. All rights reserved.
[00:00:58]
[00:00:58] Starting test execution, please wait...
[00:01:01]
[00:01:01] Total tests: 86. Passed: 86. Failed: 0. Skipped: 0.
[00:01:01] Test Run Successful.
[00:01:01] Test execution time: 2.2053 Seconds
[00:01:01] NUnit Console Runner 3.4.0
[00:01:01] Copyright (C) 2016 Charlie Poole
[00:01:01]
[00:01:01] Runtime Environment
[00:01:01] OS Version: Microsoft Windows NT 10.0.14393.0
[00:01:01] CLR Version: 4.0.30319.42000
[00:01:01]
[00:01:01] Test Files
[00:01:01] C:/projects/litjson/test/bin/Release/net45/LitJSON.Tests.dll
[00:01:01]
[00:01:02]
[00:01:02] Run Settings
[00:01:02] WorkDirectory: C:\projects\litjson
[00:01:02] ImageRuntimeVersion: 4.0.30319
[00:01:02] ImageTargetFrameworkName: .NETFramework,Version=v4.5
[00:01:02] ImageRequiresX86: False
[00:01:02] ImageRequiresDefaultAppDomainAssemblyResolver: False
[00:01:02] NumberOfTestWorkers: 2
[00:01:02]
[00:01:02] Test Run Summary
[00:01:02] Overall result: Passed
[00:01:02] Test Count: 86, Passed: 86, Failed: 0, Inconclusive: 0, Skipped: 0
[00:01:02] Start time: 2018-06-15 03:15:30Z
[00:01:02] End time: 2018-06-15 03:15:30Z
[00:01:02] Duration: 0.364 seconds
[00:01:02]
[00:01:02] Finished executing task: Test
[00:01:02]
[00:01:02] ========================================
[00:01:02] Test-SourceLink
[00:01:02] ========================================
[00:01:02] Executing task: Test-SourceLink
[00:01:04] sourcelink test passed: C:/projects/litjson/src/LitJSON/bin/Release/net20/LitJSON.dll
[00:01:05] sourcelink test passed: C:/projects/litjson/src/LitJSON/bin/Release/net35/LitJSON.dll
[00:01:06] sourcelink test passed: C:/projects/litjson/src/LitJSON/bin/Release/net40/LitJSON.dll
[00:01:06] sourcelink test passed: C:/projects/litjson/src/LitJSON/bin/Release/net45/LitJSON.dll
[00:01:07] sourcelink test passed: C:/projects/litjson/src/LitJSON/bin/Release/netstandard1.5/LitJSON.dll
[00:01:08] sourcelink test passed: C:/projects/litjson/src/LitJSON/bin/Release/netstandard2.0/LitJSON.dll
[00:01:08] Finished executing task: Test-SourceLink
[00:01:08]
[00:01:08] ========================================
[00:01:08] Package
[00:01:08] ========================================
[00:01:08] Executing task: Package
[00:01:08] Microsoft (R) Build Engine version 15.7.179.6572 for .NET Core
[00:01:08] Copyright (C) Microsoft Corporation. All rights reserved.
[00:01:08]
[00:01:09] Successfully created package 'C:/projects/litjson/artifacts/nuget\LitJson.0.13.0.nupkg'.
[00:01:09] Successfully created package 'C:/projects/litjson/artifacts/nuget\LitJson.0.13.0.symbols.nupkg'.
[00:01:09] Finished executing task: Package
[00:01:09]
[00:01:09] ========================================
[00:01:09] Upload-AppVeyor-Artifacts
[00:01:09] ========================================
[00:01:09] Executing task: Upload-AppVeyor-Artifacts
[00:01:12]
[00:01:12] Uploading artifact LitJson.0.13.0.nupkg (185,338 bytes)...36%
[00:01:12] Uploading artifact LitJson.0.13.0.nupkg (185,338 bytes)...100%
[00:01:13]
[00:01:13] Uploading artifact LitJson.0.13.0.symbols.nupkg (206,798 bytes)...32%
[00:01:13] Uploading artifact LitJson.0.13.0.symbols.nupkg (206,798 bytes)...100%
[00:01:13] Finished executing task: Upload-AppVeyor-Artifacts
[00:01:13]
[00:01:13] ========================================
[00:01:13] Publish-MyGet
[00:01:13] ========================================
[00:01:13] Executing task: Publish-MyGet
[00:01:13] Cake.exe : An error occurred when executing task 'Publish-MyGet'.
[00:01:13] At C:\projects\litjson\build.ps1:117 char:9
[00:01:13] + & "$CakeExePath" $args
[00:01:13] + ~~~~~~~~~~~~~~~~~~~~~~
[00:01:13] + CategoryInfo : NotSpecified: (An error occurr...Publish-MyGet'.:String) [], RemoteException
[00:01:13] + FullyQualifiedErrorId : NativeCommandError
[00:01:13]
[00:01:13]
[00:01:13] ----------------------------------------
[00:01:13] Teardown
[00:01:13] ----------------------------------------
[00:01:13] Executing custom teardown action...
[00:01:13] Finished running tasks.
[00:01:13] Error:
[00:01:13] One or more errors occurred.
[00:01:13]
[00:01:13]
[00:01:13]
[00:01:13] Could not resolve MyGet API key.
[00:01:13]
[00:01:13]
[00:01:13] Command executed with exception:
[00:01:13]

I just want to use this tool in unity , so I forked the project to build on appveyor under windows env. But I got this error when I built appveryor. How to solve this problem ? Or how I can get the litJson dll file?

Deserialization to Dictionary fails if a property name is a property on Dictionary

Below code reproduces this issue.

private class Event
{
    public Dictionary<string, string> Data { get; set; }
}

var json = @"{""Data"":{""Count"":""1""}}";
var ev = JsonMapper.ToObject<Event>(json);

Changing the property name "Count" to "NotCount" does not result in an exception. The problematic property names are "Comparer", "Count", "Keys", "Values".

Empty arrays in JSON strings break code.

When you use JsonMapper.ToObject on a string that contains an empty array ("somearray":[]), it seems to break things. Take this valid JSON, for example:

{
    "responseType": "success",
    "billingIsPastDue": false,
    "data": {
        "contacts": [
            {
                "id": 782,
                "first_name": "jo",
                "last_name": "schmo0",
                "phone_number": "31622255447",
                "email": null,
                "contact_owner_id": 1,
                "company_id": 2,
                "hash_tags": [], <---- EMPTY, causes issues -- see below
                "facebook": null,
                "linkedin": null,
                "twitter": null,
                "geo_location": null,
                "referred": null,
                "referral_id": "778",
                "notes": null,
                "is_blacklisted": 0,
                "contact_progress": 64
            }
        ]
    }
}

When serialized, it produces this string:

[...]
 {
        "id": 782,
        "first_name": "jo",
        "last_name": "schmo0",
        "phone_number": "31622255447",
        "email": null,
        "contact_owner_id": 1,
        "company_id": 2,
        "hash_tags": "facebook": null, <--- WOOPS, how'd this happen??
        "linkedin": null,
        "twitter": null,
        "geo_location": null,
        "referred": null,
        "referral_id": "778",
        "notes": null,
        "is_blacklisted": 0,
        "contact_progress": 64
    }
[...]

Barring this issue that I just came up on, this is a great tool and I hope to see this fixed soon :)

PrettyPrint is not working so well

This code ...

using System;
using System.Collections.Generic;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            var wr = new LitJson.JsonWriter(Console.Out);

            wr.PrettyPrint = true;
            wr.WriteArrayStart();

            foreach (KeyValuePair<string, int> kv in 
                new List<KeyValuePair<string, int>> { 
                    new KeyValuePair<string,int>("bumsti",1),
                    new KeyValuePair<string,int>("mausi",2),
                    new KeyValuePair<string,int>("zandi",3) 
                })
            {
                wr.PrettyPrint = true;
                wr.WriteObjectStart();
                wr.PrettyPrint = false;

                wr.WritePropertyName(kv.Key);
                wr.Write(kv.Value);
                wr.WriteObjectEnd();
            }

            wr.PrettyPrint = true;
            wr.WriteArrayEnd();

        }
    }
}

gives me that output:

[
    {"bumsti":1},
        {"mausi":2},
            {"zandi":3}
            ]

want to have...

[
    {"bumsti":1},
    {"mausi":2},
    {"zandi":3}
]

[Bug] - Casting Int to Float Throw InvalidCastException: Instance of JsonData doesn't hold a double

This happens when casting an integer in an array to a float.

For example:
If we have an array of int like this: [0,1,2] where we use it as a vector3. In our code, Json will throw an exception if we cast it like (float)data[0].

My workaround:
I have to do an integer cast then float cast from system. It will work if you do (float)(int)data[0]. However, you need to make sure the type is int or long, otherwise you will lose float precise for other floating point data.

Limits?

What are the litjson limitations?

Does it supports List serialization?

and more...

Thanks.

Use static property will error

` public class Value2
{
private int _x;
private int _y;
public Value2(int x, int y)
{
this._x = x;
this._y = y;
}
public static Value2 Zero
{
get
{
return new Value2(0, 0);
}
}

    public int X
    {
        get
        {
            return _x;
        }
        set
        {
            _x = value;
        }
    }
    public int Y
    {
        get
        {
            return _y;
        }
        set
        {
            _y = value;
        }
    }

    public string ToJson()
    {
        return JsonMapper.ToJson(this);
    }
}`

JsonException: Max allowed object depth reached while trying to export from type NightCee.ValueInt2 LitJson.JsonMapper.WriteValue (System.Object obj, LitJson.JsonWriter writer, Boolean writer_is_private, Int32 depth) (at Assets/Plugins/LitJson/JsonMapper.cs:701) LitJson.JsonMapper.WriteValue (System.Object obj, LitJson.JsonWriter writer, Boolean writer_is_private, Int32 depth) (at Assets/Plugins/LitJson/JsonMapper.cs:826) LitJson.JsonMapper.WriteValue (System.Object obj, LitJson.JsonWriter writer, Boolean writer_is_private, Int32 depth) (at Assets/Plugins/LitJson/JsonMapper.cs:826) LitJson.JsonMapper.WriteValue (System.Object obj, LitJson.JsonWriter writer, Boolean writer_is_private, Int32 depth) (at Assets/Plugins/LitJson/JsonMapper.cs:826) LitJson.JsonMapper.WriteValue (System.Object obj, LitJson.JsonW<message truncated>
Can you add a attribute like [JsonIgnore] to LitJson?

JsonMapper.ToJson throw InvalidCastException when enum is typeof uint

Enum like this:

enum ETest : uint
{
    A,
    B
}

JsonMapper.cs , line 807:

// Last option, let's see if it's an enum
if (obj is Enum) {
    Type e_type = Enum.GetUnderlyingType (obj_type);

    if (e_type == typeof (long)
        || e_type == typeof (uint)
        || e_type == typeof (ulong))
        writer.Write ((ulong) obj);
    else
        writer.Write ((int) obj);

    return;
}

Maybe, the cast first needs to go to uint from enum, and then to ulong. Same as long.

writer.Write ((ulong)(long) obj);
writer.Write ((ulong)(uint) obj);

ArgumentException: Duplicated Key in JsonMapper.AddObjectMetadata when instances of the same type are serialized to json for the first time in different threads

Hey,

Given a type T
if, lets say 10 threads, create each one an instances of T (or more)
when 2 or more threads attempt to serialize their own instances of T.
Then a ArgumentException saying "duplicated key" is thrown.

Why:
when the two thread serialize their instances of T, since none instances of T was serialized before, the method
private static ObjectMetadata AddObjectMetadata ( Type type ) is called.
The condition
if ( JsonMapper.objectMetadata.ContainsKey( type ) )
will evaluate to false in both threads
but at the end of the method:
objectMetadata.Add( type, data );
one of the two executions (or more) of that line will throw

Do you plan to add thread safety to LitJson or should we take precausions about this in our programs ?

Thanks you :)

Obfuscation

Hi,

I'm using port of your library for Unity 3D. Json object mapping seems to be broken when assemblies are obfuscated via CodeGuard plugin.

Is it related to reflection? Which classes should I exclude from obfuscation to make it work?

Thank you.

Serialization includes extra garbage in MonoAndroid10 build

See https://stackoverflow.com/questions/48272476/extra-garbage-produced-by-litjson-serialization-with-aws-sdk-for-monoandroid10 for details.
When I use litJson from AWSSDK.Core.3.3.19.1\lib\MonoAndroid10\AWSSDK.Core.dll the serialized output includes extra fields like "<Name>k__BackingField":"William Shakespeare". I don't understand why this only affects the MonoAndroid10 build -- it's not clear whether it's an AWSSDK build issue or a LitJSON build issue or if the different builds have different code, making it potentially a code issue.

Incorrect json string on empty arrays

    string json = @"
      {
          ""tracks"" : [ ]
      }
    ";

    JsonData js = JsonMapper.ToObject(json);
    Debug.Log(js.ToJson());

Gives next incorrect json string:

{"tracks":}

Parsing decimal/float numbers on non-english culture

Can I propose the following change in JsonReader.cs (adding numberformatinfo):

    private void ProcessNumber (string number)
    {
        if (number.IndexOf ('.') != -1 ||
            number.IndexOf ('e') != -1 ||
            number.IndexOf ('E') != -1) {

            double n_double;
            if (Double.TryParse (number, NumberStyles.Any, NumberFormatInfo.InvariantInfo, out n_double)) {
                token = JsonToken.Double;
                token_value = n_double;

                return;
            }
        }

In European cultures the decimal point is a comma and vice versa.

Danny

unable to find repository origin with: dotnet sourcelink-git origin

Hi,
I can't select the target framework and I can't build the project. I don't know if this issue is related to vs2017 or with this project and i'm pretty new to sourcelink too.

litjson

Whenever i try to build the project i've always get:
unable to find repository origin with: dotnet sourcelink-git origin

litjson-ps-build

Serializing a non-int enum member throws an InvalidCastException

Simple reproduction:

class Program
{
    enum Enum1
    {
        Hello,
        World
    }

    enum Enum2 : byte
    {
        Oh,
        No
    }

    class A
    {
        public Enum1 enum1;
    }

    class B
    {
        public Enum2 enum2;
    }

    static void Main(string[] args)
    {
        // Serializes fine :)
        System.Diagnostics.Debug.WriteLine(JsonMapper.ToJson(new A()));

        // Throws Exception :(
        System.Diagnostics.Debug.WriteLine(JsonMapper.ToJson(new B()));
    }
}

ArgumentException: not of type: Dictionary with Enum as Key

LITJson does not handle serializing/deserializing dictionaries with an enum key. For instance :

public enum MyEnum{
    cat, dog, bird
}

public void Awake(){

    var dic = new Dictionary<MyEnum,int>();

    dic.Add(MyEnum.bird,1);

    // will crash, fix is to change (string)key to key.ToString()  in JsonMapper
    var json = JsonMapper.ToJson(dic);

    // Will also crash
    var dic2 = JsonMapper.ToObject<Dictionary<MyEnum,int>>(json); 
}

In version 0.9.0 empty arrays are still handled incorrectly

class EmptyArrayTest
{
    class Data
    {
        public int[] array;
        public string name;
    }

    class Response
    {
        public JsonData data;
    }

    string testJson = @"
    {
        ""data"":
        {
            ""array"": [],
            ""name"": ""testName""
        }
    }";

    public void Run()
    {
        var response = JsonMapper.ToObject<Response>(testJson);
        JsonMapper.ToObject<Data>(response.data.ToJson());
    }
}

As of latest commit (e16713d) this code generates a JsonException: Can't assign value 'name' (type System.String) to type System.Int32[]

Support for .NET Framework 2.0

Version 0.9.0.0 of the library offered a .NET 2.0 build, while currently .NET 3.5 seems to be the oldest .NET Framework supported. Is there a reason to drop support for .NET 2.0 (e.g Json.NET still supports .NET 2.0)?

LitJson reading from a network stream blocks even when a complete object is read

When LitJson creates a JsonReader from a NetworkStream, it will continue to attempt to read even after a complete Json object has been parsed.

This read will block and not return the Json object.

The block happens in the lexer (which is correct, it should if it is in the middle of parsing an object until the rest of the object arrives on the stream):

        private int NextChar ()
        {
            if (input_buffer != 0) {
                int tmp = input_buffer;
                input_buffer = 0;

                return tmp;
            }

            return reader.Read ();
        }

Here is block of code that demonstrates the bug:

            NetworkStream stream = tcpClient.GetStream();
            while (keepReading)
            {
                keepReading = (null != tcpClient) && tcpClient.Connected;
                if (keepReading)
                {
                    System.IO.TextReader tr = new System.IO.StreamReader(stream);
                    JsonReader jsonReader = new JsonReader(tr);

                    // this will block on a network stream
                    JsonData result = JsonMapper.ToObject(jsonReader);

                    // with the bug, this line is never reached
                    System.Console.WriteLine(result.ToJson());
                }
            }

The expected behavior is that JsonMapper.ToObject (and all variants), will return when a complete Json object has been parsed from the stream. If the stream has fragments of another message not yet complete, JsonMapper.ToObject should first return the complete message, then in the next iteration, block on the stream until the rest of the next message arrives and return that object, etc...

Here is a complete c# program that can be used to reproduce and debug the problem:

using System;
using System.Threading;
using System.Net;
using System.Net.Sockets;
using LitJson;

// pulled from another project. The threading model is preserved
// in case it is at all relevant to reproducing the bug.
namespace LitJsonNetworkTest
{
    public class ServerConnection
    {
        private TcpClient tcpClient = null;
        private Thread networkReadThread = null;

        public ServerConnection()
        {
        }

        public void Wait()
        {
            networkReadThread.Join();
        }
        public void ConnectTo(string a, int p)
        {
            tcpClient = new TcpClient(a, p);
            networkReadThread = new Thread(NetworkReadThread);
            networkReadThread.Start();
        }

        void NetworkReadThread()
        {
            bool keepReading = (null != tcpClient);
            NetworkStream stream = tcpClient.GetStream();
            while (keepReading)
            {
                keepReading = (null != tcpClient) && tcpClient.Connected;
                try
                {
                    if (keepReading)
                    {
                        System.IO.TextReader tr = new System.IO.StreamReader(stream);
                        JsonReader jsonReader = new JsonReader(tr);

                        // this will block on a network stream
                        JsonData result = JsonMapper.ToObject(jsonReader);

                        // with the bug, this line is never reached
                        System.Console.WriteLine(result.ToJson());
                    }
                }
                catch (System.Exception e)
                {
                    string errorMessage = "Connection exception: " + e.Message + "\nStack Trace " + e.StackTrace;
                    string stackTrace = e.StackTrace;
                    System.Console.WriteLine(errorMessage);
                    throw (e);
                }
            }
        }
    }

    class Session
    {
        private TcpClient m_tcpClient = null;
        private Thread m_workerThread = null;

        public Session(TcpClient client)
        {
            if (null != client)
            {
                m_tcpClient = client;
                m_workerThread = new Thread(this.Start);
                m_workerThread.Start();
            }
            else if (null != client)
            {
                m_tcpClient = client;
                Shutdown();
            }
        }

        private void Wait()
        {
            m_workerThread.Join();
        }

        void Send(string payload)
        {
            byte[] responseBytes = System.Text.Encoding.ASCII.GetBytes(payload);
            m_tcpClient.GetStream().Write(responseBytes, 0, payload.Length);
        }

        void Shutdown()
        {
            m_tcpClient.Close();
        }

        private void Start()
        {
            try
            {
                Send("{\"playerId\":\"[email protected]\",\"randomData\":\"dooblydoo\"}");
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                Console.WriteLine(e.StackTrace);
                Shutdown();
                return;
            }
        }
    }

    class Server
    {
        private IPAddress m_listenAddress = IPAddress.Parse("0.0.0.0");
        private TcpListener m_server = null;
        private Thread m_workerThread = null;

        public Server()
        {
            m_server = new TcpListener(m_listenAddress, 42424);
            m_workerThread = new Thread(this.Start);
            m_workerThread.Start();
        }

        public void wait()
        {
            m_workerThread.Join();
        }

        private void Start()
        {
            try
            {
                m_server.Start(64);
                while(true)
                {
                    TcpClient client = m_server.AcceptTcpClient();
                    if(null != client)
                    {
                        Session s = new Session(client);
                    }
                }
            }
            catch(Exception e)
            {
                Console.WriteLine(e.Message);
                Console.WriteLine(e.StackTrace);
            }
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Server s = new Server();

            ServerConnection server = new ServerConnection();
            server.ConnectTo("127.0.0.1", 42424);
            server.Wait();
            s.wait();
        }
    }
}

I would not be surprised it this is actually user error, but this seems like a reasonable usage of passing a TextStream to JsonWrapper/JsonReader.

I will dig through the source to see if there is a sane way to support the expected behavior.

JsonWriter: add ability to pass JsonData

hey :) i needed to compose a previously computed json as object inside another json attribute, so i edited the jsonwriter source code and copy pasted the write(string) removing string escaping. now it works well :)

if you need i can provide source code :)

Can I ignore some certain properties whose modifier is PUBLIC when I serialize an object ?

For example , class 'Test' implement interface 'ITest' ,as you know, class 'Test' must has some PUBLIC properties what defined in the interface.But I don't want to serialize the property,so what should I do?
Below is the example-code:

        interface ITest
        {
            int TestProperty { get; }
        }
        class Test : ITest
        {
            //The property what I want not to serialize
            public int TestProperty => 0;
            public int Other { get; set; } = 1;
        }

        . . .

        Test t = new Test();
        string result = LitJson.JsonMapper.ToJson(t);

I look forward to your reply :)

Assignment error

HI,This is my codes:

string value = "bbb";
string jsonContext = "{"type2" :{ "type3": { "type4": "aaa" } } }";
JsonData jd = JsonMapper.ToObject(jsonContext);
Console.WriteLine(jd.ToJson());

jd["type2"]["type3"]["type4"] = value;
Console.WriteLine(jd["type2"]["type3"]["type4"].ToJson());
Console.WriteLine(jd["type2"]["type3"].ToJson());
Console.WriteLine(jd["type2"].ToJson());
Console.WriteLine(jd.ToJson());
Console.ReadKey();

but,print is:
{"type2":{"type3":{"type4":"aaa"}}}
"bbb"
{"type4":"bbb"}
{"type3":{"type4":"bbb"}}
{"type2":{"type3":{"type4":"aaa"}}}

i think last print is:
{"type2":{"type3":{"type4":"bbb"}}}

This is my problem,Thank You.

Bug- InvalidCastException: Instance of JsonData doesn't hold a string

Hi, I try to call JsonMapper.ToObject(json). The json data as below:
string json = @"{""body"":{""class"":[{""url"":""http://m.api.deepoon.com/app/getGameTop""},{""url"":""http://m.api.deepoon.com/app/getGameTop""}]},""header"":{""retMessage"":""ok"",""retStatus"":200},""page"":[]}";
I always get InvalidCastException when running on my android device. Could u have a try? And tell me what's wrong? Great thanks.

null value not handled gracefully in ToJson()

Following code result in an error

    string json_str = @"{
        ""name""  : ""Bill"",
        ""age""   : 32,
        ""awake"" : true,
        ""n""     : 1994.0226,
        ""note""  : [ ""life"", ""is"", ""but"", ""a"", ""dream"" ],
        ""null_str"" : null
      }";


    JsonData json = JsonMapper.ToObject(json_str);
    Console.WriteLine(json.ToJson());

NullReferenceException: Object reference not set to an instance of an object
LitJson.JsonData.WriteJson (IJsonWrapper obj, LitJson.JsonWriter writer) (at Assets/LitJson/JsonData.cs:795)
LitJson.JsonData.WriteJson (IJsonWrapper obj, LitJson.JsonWriter writer) (at Assets/LitJson/JsonData.cs:840)
LitJson.JsonData.ToJson () (at Assets/LitJson/JsonData.cs:972)

Please support RFC 7159

The current LitJSON is based on RFC 4627 obsoleted by RFC 7159 ( https://tools.ietf.org/html/rfc7159 ).
There are many changes between them.

The trouble I felled into is that:

var result = LitJson.JsonMapper.ToObject<string>("\"foo\"");

throws an exception.

In Appendix A of RFC 7159:

  • Changed the definition of "JSON text" so that it can be any JSON value, removing the constraint that it be an object or array.

So, the result should be "foo" with no exception.

The following patch can fix the above problem:

--- JsonReader.cs.orig  2015-07-02 18:29:53.554902400 +0900
+++ JsonReader.cs   2015-07-02 18:23:18.075301700 +0900
@@ -215,10 +215,20 @@
                          '"');

             TableAddRow (ParserToken.Text);
+            TableAddCol (ParserToken.Text, '"',
+                         (int) ParserToken.String);
             TableAddCol (ParserToken.Text, '[',
                          (int) ParserToken.Array);
             TableAddCol (ParserToken.Text, '{',
                          (int) ParserToken.Object);
+            TableAddCol (ParserToken.Text, (int) ParserToken.Number,
+                         (int) ParserToken.Number);
+            TableAddCol (ParserToken.Text, (int) ParserToken.True,
+                         (int) ParserToken.True);
+            TableAddCol (ParserToken.Text, (int) ParserToken.False,
+                         (int) ParserToken.False);
+            TableAddCol (ParserToken.Text, (int) ParserToken.Null,
+                         (int) ParserToken.Null);

             TableAddRow (ParserToken.Value);
             TableAddCol (ParserToken.Value, '"',

Issue Serializing struct with a public static getter

For whatever reason, I would get an infinite loop of recursion in "WriteValue" within the JsonMapper.cs (I believe from line 808) whenever serializing my struct that had this:
public static MyStruct zero { get { return new MyStruct(0,0); } }

It would eventually error out with a maxDepth error once depth hit 101 (an expected max depth)

Adding the second check to my new line 814 fixed the issue:
if (p_info.CanRead && !p_info.GetGetMethod().IsStatic) {

Hope this helps!
Thanks for your time,
Steven

Mature/Fixed/Centralized fork?

Appears that this original project is "dead". I saw many forks with fixing and improved stuff. Which one should be considered a centralized / mature one?

If none, we have a candidate to help to organize and merge the pull requests?

中文乱码

JsonData中有中文时,JsonMapper.ToJson(jsonData)返回乱码。
请问怎么解决?谢谢!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.