master
Harald Wolff-Thobaben 2020-11-18 00:36:18 +01:00
parent fe84a42334
commit c9f5146dbd
24 changed files with 576 additions and 5586 deletions

View File

@ -0,0 +1,60 @@
using ln.json.mapping;
using System;
using System.IO;
namespace ln.json
{
public abstract class JSONMappedObject
{
FileSystemWatcher watcher;
string jsonFileName;
object o;
public JSONMappedObject() { }
public JSONMappedObject(String jsonFile)
{
this.jsonFileName = jsonFile;
this.o = this;
watcher = new FileSystemWatcher(Path.GetDirectoryName(jsonFile));
watcher.Filter = Path.GetFileName(jsonFile);
watcher.Changed += (s, e) => mapJSON();
watcher.Created += (s, e) => mapJSON();
watcher.EnableRaisingEvents = true;
mapJSON();
}
public JSONMappedObject(String jsonFile,object o)
{
this.jsonFileName = jsonFile;
this.o = o;
watcher = new FileSystemWatcher(Path.GetDirectoryName(jsonFile));
watcher.Filter = Path.GetFileName(jsonFile);
watcher.Changed += (s, e) => mapJSON();
watcher.Created += (s, e) => mapJSON();
watcher.EnableRaisingEvents = true;
mapJSON();
}
void mapJSON()
{
//Logging.Log(LogLevel.DEBUG, "File {0} changed. Remapping...", jsonFileName);
if (File.Exists(jsonFileName))
{
JSONValue jsonValue = JSONParser.ParseFile(jsonFileName);
if (jsonValue is JSONObject jsonObject)
{
JSONMapper mapper = new JSONMapper();
mapper.Apply(jsonObject, this.o);
}
}
}
}
}

View File

@ -1,6 +1,7 @@
using System;
using System.Globalization;
using ln.types;
using ln.type;
namespace ln.json
{
public class JSONNumber : JSONValue

View File

@ -1,10 +1,7 @@
using System;
using System.Text;
using System.Collections.Generic;
using System.Reflection;
using System.Linq;
using System.Security.Cryptography;
using ln.types.btree;
using ln.collections;
using ln.json.mapping;
namespace ln.json
@ -36,7 +33,10 @@ namespace ln.json
}
public JSONObject Add(string propertyName, object value)
{
values[propertyName] = JSONMapper.DefaultMapper.ToJson(value);
if (JSONMapper.DefaultMapper.Serialize(value,out JSONValue jsonValue))
{
values[propertyName] = jsonValue;
}
return this;
}
@ -47,7 +47,11 @@ namespace ln.json
public T ToObject<T>()
{
return JSONMapper.DefaultMapper.FromJson<T>(this);
if (JSONMapper.DefaultMapper.Deserialize(this, typeof(T), out object o))
{
return (T)o;
}
throw new NotSupportedException();
}
public override string ToString()
@ -76,7 +80,11 @@ namespace ln.json
public static JSONObject From(object value)
{
return (JSONObject)JSONMapper.DefaultMapper.ToJson(value);
if (JSONMapper.DefaultMapper.Serialize(value, out JSONValue json))
{
return (JSONObject)json;
}
throw new NotSupportedException();
}
}

View File

@ -8,11 +8,11 @@
// *
// **/
using System;
using System.Collections.Generic;
using ln.types;
using ln.types.stream;
using ln.type;
using System.Text;
using System.Globalization;
using System.IO;
namespace ln.json
{
public class JSONParser
@ -24,41 +24,47 @@ namespace ln.json
public static JSONValue Parse(String jsonSource)
{
CharStream chars = new CharStream(jsonSource);
return ParseValue(chars);
return ParseValue(new StringReader(jsonSource));
}
public static JSONValue Parse(TextReader reader) => ParseValue(reader);
public static JSONValue ParseFile(string filename)
{
using (StreamReader streamReader = new StreamReader(filename))
return ParseValue(streamReader);
}
/**
* Für alle Parser Methoden welche als Parameter ein CharStream erhalten
* gilt folgendes:
*
* - CharStream.Current zeitg auf das erste Zeichen,
* welches interpretiert werden soll
* - Bei Rücksprung zeigt CharStream.Current auf das erste zeichen,
* welches nicht mehr zum aktuellen Wert gehört und kein Whitespace
* ist
*
**/
static JSONValue ParseValue(CharStream chars)
static void SkipWhitespace(TextReader reader)
{
chars.Skip(char.IsWhiteSpace);
switch (chars.Current)
while (char.IsWhiteSpace((char) reader.Peek()) && (reader.Peek()!=-1))
reader.Read();
}
static void Read(TextReader reader, StringBuilder stringBuilder, Func<char, bool> condition)
{
int ch;
while (condition((char) (ch = reader.Peek())) && (ch!=-1))
stringBuilder.Append((char)reader.Read());
}
static JSONValue ParseValue(TextReader reader)
{
SkipWhitespace(reader);
switch (reader.Peek())
{
case '"':
return parseString(chars);
return parseString(reader);
case 't':
return parseTrue(chars);
return parseTrue(reader);
case 'f':
return parseFalse(chars);
return parseFalse(reader);
case 'n':
return parseNull(chars);
return parseNull(reader);
case '[':
return parseArray(chars);
return parseArray(reader);
case '{':
return parseObject(chars);
return parseObject(reader);
case '0':
case '1':
case '2':
@ -70,163 +76,199 @@ namespace ln.json
case '8':
case '9':
case '-':
return parseNumber(chars);
return parseNumber(reader);
default:
throw new FormatException(String.Format("Unexpected character: {0} [ 0x{0:x4} ]", chars.Current));
throw new FormatException(String.Format("Unexpected character: {0} [ 0x{0:x4} ]", reader.Peek()));
}
}
static JSONString parseString(CharStream chars)
static JSONString parseString(TextReader reader)
{
if (chars.Current != '"')
if (reader.Peek() != '"')
throw new FormatException("Unexpected character");
StringBuilder stringBuilder = new StringBuilder();
chars.MoveNext();
while (chars.Current != '"')
reader.Read();
int ch;
while ((ch = reader.Read()) != '"')
{
stringBuilder.Append(chars.Current);
if (chars.Current == '\\')
{
chars.MoveNext();
stringBuilder.Append(chars.Current);
}
chars.MoveNext();
if (ch == -1)
throw new EndOfStreamException();
stringBuilder.Append((char) ch);
if (ch == '\\')
stringBuilder.Append((char) reader.Read());
// if (ch == '\\')
// {
// ch = reader.Read();
// if (ch == -1)
// throw new EndOfStreamException();
// switch (ch)
// {
// case '\\':
// stringBuilder.Append('\\');
// break;
// case '/':
// stringBuilder.Append('/');
// break;
// case 'b':
// stringBuilder.Append('\b');
// break;
// case 'f':
// stringBuilder.Append('\f');
// break;
// case 'n':
// stringBuilder.Append('\n');
// break;
// case 'r':
// stringBuilder.Append('\r');
// break;
// case 't':
// stringBuilder.Append('\t');
// break;
// case '"':
// stringBuilder.Append('"');
// break;
// case 'u':
// char[] hexDigits = new char[4];
// reader.ReadBlock(hexDigits, 0, 4);
// ch = int.Parse(hexDigits, System.Globalization.NumberStyles.HexNumber);
// stringBuilder.Append((char) ch);
// break;
// default:
// throw new FormatException();
// }
// }
// else
// stringBuilder.Append((char) ch);
}
chars.TryNext();
chars.Skip(char.IsWhiteSpace);
SkipWhitespace(reader);
return new JSONString(JSONString.Unescape(stringBuilder.ToString()));
}
static JSONNumber parseNumber(CharStream chars)
static JSONNumber parseNumber(TextReader reader)
{
StringBuilder sb = new StringBuilder();
if (chars.Current == '-')
if (reader.Peek() == '-')
{
sb.Append(chars.Current);
chars.MoveNext();
sb.Append((char)reader.Read());
}
sb.Append(chars.Read(char.IsDigit));
if (chars.Current == '.')
Read(reader,sb,char.IsDigit);
if (reader.Peek() == '.')
{
sb.Append('.');
chars.MoveNext();
sb.Append(chars.Read(char.IsDigit));
reader.Read();
Read(reader,sb,char.IsDigit);
}
if ((chars.Current == 'e')|| (chars.Current == 'E'))
if ((reader.Peek() == 'e') || (reader.Peek() == 'E'))
{
sb.Append('e');
if ((chars.Current == '-')|| (chars.Current == '+'))
if ((reader.Peek() == '-')|| (reader.Peek() == '+'))
{
sb.Append(chars.Current);
chars.MoveNext();
sb.Append((char)reader.Read());
}
sb.Append(chars.Read(char.IsDigit));
Read(reader, sb, char.IsDigit);
}
chars.Skip(char.IsWhiteSpace);
SkipWhitespace(reader);
return new JSONNumber(decimal.Parse(sb.ToString(),CultureInfo.InvariantCulture));
}
static JSONArray parseArray(CharStream chars)
static JSONArray parseArray(TextReader reader)
{
if (chars.Current != '[')
if (reader.Peek() != '[')
throw new FormatException("Unexpected character");
JSONArray array = new JSONArray();
chars.MoveNext();
while (chars.Current != ']')
reader.Read();
while (reader.Peek() != ']')
{
array.Add(ParseValue(chars));
if (chars.Current == ',')
array.Add(ParseValue(reader));
if (reader.Peek() == ',')
{
chars.MoveNext();
chars.Skip(char.IsWhiteSpace);
reader.Read();
SkipWhitespace(reader);
}
}
chars.TryNext();
chars.Skip(char.IsWhiteSpace);
reader.Read();
SkipWhitespace(reader);
return array;
}
static JSONObject parseObject(CharStream chars)
static JSONObject parseObject(TextReader reader)
{
if (chars.Current != '{')
if (reader.Peek() != '{')
throw new FormatException("Unexpected character");
JSONObject o = new JSONObject();
chars.MoveNext();
chars.Skip(char.IsWhiteSpace);
reader.Read();
SkipWhitespace(reader);
while (chars.Current != '}')
while (reader.Peek() != '}')
{
JSONString s = parseString(chars);
if (chars.Current != ':')
JSONString s = parseString(reader);
if (reader.Peek() != ':')
throw new FormatException("expected :");
chars.MoveNext();
o.Add(s.Value, ParseValue(chars));
reader.Read();
o.Add(s.Value, ParseValue(reader));
if (chars.Current == ',')
if (reader.Peek() == ',')
{
chars.MoveNext();
chars.Skip(char.IsWhiteSpace);
reader.Read();
SkipWhitespace(reader);
}
}
chars.TryNext();
chars.Skip(char.IsWhiteSpace);
reader.Read();
SkipWhitespace(reader);
return o;
}
static JSONTrue parseTrue(CharStream chars)
static JSONTrue parseTrue(TextReader reader)
{
char[] ch = new char[4];
for (int n = 0; n < ch.Length; n++)
{
ch[n] = chars.Current;
chars.MoveNext();
ch[n] = (char)reader.Read();
}
if (ch.AreEqual(chTrue))
{
chars.Skip(char.IsWhiteSpace);
SkipWhitespace(reader);
return JSONTrue.Instance;
}
throw new FormatException();
}
static JSONFalse parseFalse(CharStream chars)
static JSONFalse parseFalse(TextReader reader)
{
char[] ch = new char[5];
for (int n = 0; n < ch.Length; n++)
{
ch[n] = chars.Current;
chars.MoveNext();
ch[n] = (char)reader.Read();
}
if (ch.AreEqual(chFalse))
{
chars.Skip(char.IsWhiteSpace);
SkipWhitespace(reader);
return JSONFalse.Instance;
}
throw new FormatException();
}
static JSONNull parseNull(CharStream chars)
static JSONNull parseNull(TextReader reader)
{
char[] ch = new char[4];
for (int n=0;n<ch.Length;n++)
{
ch[n] = chars.Current;
chars.MoveNext();
ch[n] = (char)reader.Read();
}
if (ch.AreEqual(chNull))
{
chars.Skip(char.IsWhiteSpace);
SkipWhitespace(reader);
return JSONNull.Instance;
}

View File

@ -1,26 +0,0 @@
using System.Reflection;
using System.Runtime.CompilerServices;
// Information about this assembly is defined by the following attributes.
// Change them to the values specific to your project.
[assembly: AssemblyTitle("ln.json")]
[assembly: AssemblyDescription("JSON Implementation")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("")]
[assembly: AssemblyCopyright("")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}".
// The form "{Major}.{Minor}.*" will automatically update the build and revision,
// and "{Major}.{Minor}.{Build}.*" will update just the revision.
[assembly: AssemblyVersion("1.0.*")]
// The following attributes are used to specify the signing key for the assembly,
// if desired. See the Mono documentation for more information about signing.
//[assembly: AssemblyDelaySign(false)]
//[assembly: AssemblyKeyFile("")]

View File

@ -1,63 +0,0 @@
using System;
using System.IO;
using ln.json;
using ln.json.mapping;
namespace json.test
{
class MainClass
{
static string[] sources = {
"\"I am a string\"",
"{ \"me\" : \"is a string too\"}",
"[ \"this\", \"is\", \"an\", \"array\" ]"
};
public static void Main(string[] args)
{
JSONObject json = new JSONObject()
.Add("version", new JSONNumber(123.456))
.Add("text", new JSONString("Ich bin ein Text! Lächerlich, oder?"))
.Add("Obst",new JSONArray()
.Add(new JSONString("Apfel"))
.Add(new JSONString("Birne"))
.Add(new JSONString("Zwetschge"))
.Add(JSONNull.Instance)
.Add(JSONTrue.Instance)
.Add(JSONFalse.Instance)
)
;
Console.WriteLine(json.ToString());
JSONValue json2 = JSONParser.Parse(json.ToString());
Console.WriteLine(json2.ToString());
JSONValue value = JSONParser.Parse(File.ReadAllText("test.json"));
Console.WriteLine("");
Console.WriteLine("test.json file:");
Console.WriteLine("PARSED: {0}",value.ToString());
Person person = new Person()
{
firstname = "Harald",
lastname = "Wolff-Thobaben",
age = 39
};
JSONValue jsonPerson = JSONMapper.DefaultMapper.ToJson(person);
Console.WriteLine(jsonPerson.ToString());
Person p2 = JSONMapper.DefaultMapper.FromJson<Person>(jsonPerson);
}
class Person
{
public string firstname;
public string lastname;
public int age;
}
}
}

View File

@ -1,26 +0,0 @@
using System.Reflection;
using System.Runtime.CompilerServices;
// Information about this assembly is defined by the following attributes.
// Change them to the values specific to your project.
[assembly: AssemblyTitle("json.test")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("")]
[assembly: AssemblyCopyright("")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}".
// The form "{Major}.{Minor}.*" will automatically update the build and revision,
// and "{Major}.{Minor}.{Build}.*" will update just the revision.
[assembly: AssemblyVersion("1.0.*")]
// The following attributes are used to specify the signing key for the assembly,
// if desired. See the Mono documentation for more information about signing.
//[assembly: AssemblyDelaySign(false)]
//[assembly: AssemblyKeyFile("")]

View File

@ -1,48 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{49FFBD9F-655E-4C74-A078-99B5E09059C6}</ProjectGuid>
<OutputType>Exe</OutputType>
<RootNamespace>json.test</RootNamespace>
<AssemblyName>json.test</AssemblyName>
<TargetFrameworkVersion>v4.7</TargetFrameworkVersion>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug</OutputPath>
<DefineConstants>DEBUG;</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<ExternalConsole>true</ExternalConsole>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<Optimize>true</Optimize>
<OutputPath>bin\Release</OutputPath>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<ExternalConsole>true</ExternalConsole>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
</ItemGroup>
<ItemGroup>
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\ln.json.csproj">
<Project>{D9342117-3249-4D8B-87C9-51A50676B158}</Project>
<Name>ln.json</Name>
</ProjectReference>
</ItemGroup>
<ItemGroup>
<None Include="test.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup>
<Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
</Project>

View File

@ -1,7 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup Condition=" '$(RunConfiguration)' == 'Default' ">
<StartAction>Project</StartAction>
<ExternalConsole>false</ExternalConsole>
</PropertyGroup>
</Project>

View File

@ -1,317 +0,0 @@
[
{
"_id": "59f1e59e0f93b5501585651d",
"index": 0,
"guid": "e88f3f2a-3253-4137-9169-b4410c2b806e",
"isActive": true,
"balance": "$2,448.63",
"picture": "http://placehold.it/32x32",
"age": 20,
"eyeColor": "green",
"name": "Kim Trevino",
"gender": "female",
"company": "FROSNEX",
"email": "kimtrevino@frosnex.com",
"phone": "+1 (828) 501-2822",
"address": "309 Forrest Street, Waiohinu, Mississippi, 4324",
"about": "Excepteur sit veniam consequat nostrud minim quis enim aliqua est eiusmod laboris culpa. Eiusmod duis culpa dolor excepteur voluptate ullamco et. Laborum nostrud amet magna in anim qui ad exercitation velit nostrud. Magna est voluptate mollit ipsum incididunt officia.\r\n",
"registered": "2016-04-22T11:29:02 -02:00",
"latitude": 63.703284,
"longitude": 155.700614,
"tags": [
"quis",
"Lorem",
"dolor",
"do",
"nisi",
"cupidatat",
"dolor"
],
"friends": [
{
"id": 0,
"name": "Baird Hubbard"
},
{
"id": 1,
"name": "Marie Strong"
},
{
"id": 2,
"name": "Millie Armstrong"
}
],
"greeting": "Hello, Kim Trevino! You have 5 unread messages.",
"favoriteFruit": "strawberry"
},
{
"_id": "59f1e59e5ccd12f718d4abef",
"index": 1,
"guid": "4d89ade0-1061-4f5f-8a1f-32146e1fe346",
"isActive": true,
"balance": "$3,468.56",
"picture": "http://placehold.it/32x32",
"age": 22,
"eyeColor": "blue",
"name": "Cote Case",
"gender": "male",
"company": "GEEKNET",
"email": "cotecase@geeknet.com",
"phone": "+1 (805) 553-3611",
"address": "251 Highlawn Avenue, Berwind, Kentucky, 7590",
"about": "Consectetur quis Lorem ut duis sunt Lorem reprehenderit dolore proident ullamco qui irure veniam cupidatat. Non deserunt adipisicing occaecat est culpa fugiat pariatur nostrud est officia esse proident culpa. Anim velit dolore pariatur adipisicing sint ullamco dolor enim voluptate excepteur eu do laboris do. Voluptate nostrud ullamco sit labore. Ad do commodo amet aliquip laboris sit irure qui aliqua dolore labore.\r\n",
"registered": "2016-08-03T04:34:48 -02:00",
"latitude": 28.463579,
"longitude": 35.373716,
"tags": [
"quis",
"irure",
"qui",
"officia",
"aliquip",
"amet",
"est"
],
"friends": [
{
"id": 0,
"name": "Johanna Larsen"
},
{
"id": 1,
"name": "Richmond Ward"
},
{
"id": 2,
"name": "Dominique Ramirez"
}
],
"greeting": "Hello, Cote Case! You have 5 unread messages.",
"favoriteFruit": "strawberry"
},
{
"_id": "59f1e59e1572c7a9c1da5405",
"index": 2,
"guid": "ab370e92-a65d-47a2-bd7b-dec38a80ee09",
"isActive": false,
"balance": "$1,297.48",
"picture": "http://placehold.it/32x32",
"age": 37,
"eyeColor": "green",
"name": "Haley Brewer",
"gender": "male",
"company": "ZILLAR",
"email": "haleybrewer@zillar.com",
"phone": "+1 (843) 583-2641",
"address": "496 Emmons Avenue, Enetai, Arizona, 7650",
"about": "Do velit et adipisicing do aute exercitation quis incididunt duis ad aliquip aliqua excepteur. Veniam fugiat ipsum do magna anim ad dolor. Ex sunt aliquip amet ea occaecat nisi quis in do eiusmod ex sit deserunt. Est exercitation do ex cupidatat tempor voluptate ut Lorem consequat. Aliquip non sunt nostrud veniam. Sit in in fugiat eu magna exercitation irure cillum labore.\r\n",
"registered": "2016-05-01T06:57:55 -02:00",
"latitude": -42.360466,
"longitude": -60.960653,
"tags": [
"eiusmod",
"sint",
"pariatur",
"do",
"ullamco",
"cupidatat",
"id"
],
"friends": [
{
"id": 0,
"name": "Jenny Horne"
},
{
"id": 1,
"name": "Minnie Leach"
},
{
"id": 2,
"name": "Guthrie Maxwell"
}
],
"greeting": "Hello, Haley Brewer! You have 8 unread messages.",
"favoriteFruit": "apple"
},
{
"_id": "59f1e59e7b95bc5299c9f2d1",
"index": 3,
"guid": "b46a8b03-8417-44d2-a54b-5646bd0d281c",
"isActive": true,
"balance": "$3,264.43",
"picture": "http://placehold.it/32x32",
"age": 33,
"eyeColor": "blue",
"name": "Snow Shaffer",
"gender": "male",
"company": "SNOWPOKE",
"email": "snowshaffer@snowpoke.com",
"phone": "+1 (828) 473-3114",
"address": "992 Dearborn Court, Logan, Federated States Of Micronesia, 6556",
"about": "Laborum aliquip aute pariatur cupidatat pariatur ea. Et mollit consequat nulla ullamco non officia pariatur ex incididunt sunt adipisicing reprehenderit velit. Ullamco non laborum elit fugiat. Sint cillum voluptate ullamco fugiat reprehenderit qui mollit velit. Aliqua aliquip elit aliquip Lorem veniam pariatur esse cillum nisi officia cillum quis labore.\r\n",
"registered": "2016-03-18T08:16:13 -01:00",
"latitude": -64.030865,
"longitude": -88.34457,
"tags": [
"magna",
"proident",
"magna",
"excepteur",
"non",
"et",
"sit"
],
"friends": [
{
"id": 0,
"name": "Lawson Brennan"
},
{
"id": 1,
"name": "Daniels Carson"
},
{
"id": 2,
"name": "Horn Hood"
}
],
"greeting": "Hello, Snow Shaffer! You have 2 unread messages.",
"favoriteFruit": "apple"
},
{
"_id": "59f1e59e0db09a4c480e75d6",
"index": 4,
"guid": "c7cf2208-9e20-4e9f-b670-2cdb74d7699a",
"isActive": false,
"balance": "$2,175.68",
"picture": "http://placehold.it/32x32",
"age": 35,
"eyeColor": "green",
"name": "Kramer Pollard",
"gender": "male",
"company": "DOGNOSIS",
"email": "kramerpollard@dognosis.com",
"phone": "+1 (934) 580-2560",
"address": "732 Folsom Place, Whitehaven, Maryland, 8572",
"about": "Ad minim laboris officia quis. Anim nulla et adipisicing sit est cupidatat ex nostrud ullamco mollit aute. Ipsum qui sunt enim quis adipisicing id ea cillum nulla. Adipisicing elit dolore veniam eu sint aliqua non ea adipisicing. Nulla Lorem nulla pariatur amet exercitation magna labore ea. Labore commodo in cupidatat minim cupidatat.\r\n",
"registered": "2015-02-07T09:09:00 -01:00",
"latitude": 83.970257,
"longitude": -114.00038,
"tags": [
"laboris",
"aliquip",
"ea",
"sint",
"dolor",
"veniam",
"est"
],
"friends": [
{
"id": 0,
"name": "Kinney Owen"
},
{
"id": 1,
"name": "Hess Reese"
},
{
"id": 2,
"name": "Morse Hurley"
}
],
"greeting": "Hello, Kramer Pollard! You have 6 unread messages.",
"favoriteFruit": "strawberry"
},
{
"_id": "59f1e59edb953c54accaa548",
"index": 5,
"guid": "be93d4ca-347b-4c97-9433-99b5cfd12e16",
"isActive": true,
"balance": "$2,725.10",
"picture": "http://placehold.it/32x32",
"age": 22,
"eyeColor": "green",
"name": "Turner Robinson",
"gender": "male",
"company": "FIREWAX",
"email": "turnerrobinson@firewax.com",
"phone": "+1 (949) 533-3924",
"address": "331 Throop Avenue, Brady, Ohio, 919",
"about": "Id exercitation aute elit in duis laboris dolore. Occaecat nulla amet elit pariatur ipsum culpa mollit ad Lorem mollit. Magna ex labore elit do deserunt deserunt laboris ipsum. Est nostrud qui nulla adipisicing Lorem enim occaecat excepteur sint id quis dolor minim enim. Adipisicing consequat ut ad sint sunt enim. Laborum sint officia pariatur ea non dolor aliquip officia veniam qui minim velit ea nostrud. Amet dolore cupidatat velit laboris fugiat aute veniam sint aliqua fugiat nostrud anim incididunt et.\r\n",
"registered": "2015-08-21T07:41:31 -02:00",
"latitude": -51.608905,
"longitude": -169.745012,
"tags": [
"amet",
"laborum",
"esse",
"nulla",
"tempor",
"nisi",
"cillum"
],
"friends": [
{
"id": 0,
"name": "Gina Holden"
},
{
"id": 1,
"name": "Kane Wolf"
},
{
"id": 2,
"name": "Dorsey Pate"
}
],
"greeting": "Hello, Turner Robinson! You have 3 unread messages.",
"favoriteFruit": "apple"
},
{
"_id": "59f1e59e9891229ca4cc0322",
"index": 6,
"guid": "1b7258b3-dd5d-4dc6-a7ee-1c5398d2b442",
"isActive": true,
"balance": "$1,060.29",
"picture": "http://placehold.it/32x32",
"age": 20,
"eyeColor": "blue",
"name": "Byers Rojas",
"gender": "male",
"company": "CHORIZON",
"email": "byersrojas@chorizon.com",
"phone": "+1 (804) 553-3001",
"address": "598 McKinley Avenue, Roosevelt, American Samoa, 6741",
"about": "Sunt ullamco mollit et dolore ut. Et aliquip ipsum laboris id et nulla ipsum consequat adipisicing. Eiusmod enim ad sunt nisi nulla sit Lorem pariatur.\r\n",
"registered": "2016-08-27T09:48:41 -02:00",
"latitude": -48.874859,
"longitude": 73.09912,
"tags": [
"voluptate",
"esse",
"sunt",
"do",
"aute",
"laborum",
"deserunt"
],
"friends": [
{
"id": 0,
"name": "Rosanne Benjamin"
},
{
"id": 1,
"name": "Beach Doyle"
},
{
"id": 2,
"name": "Ella Collier"
}
],
"greeting": "Hello, Byers Rojas! You have 9 unread messages.",
"favoriteFruit": "apple"
}
]

View File

@ -1,79 +1,15 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{D9342117-3249-4D8B-87C9-51A50676B158}</ProjectGuid>
<OutputType>Library</OutputType>
<RootNamespace>ln.json</RootNamespace>
<AssemblyName>ln.json</AssemblyName>
<TargetFrameworkVersion>v4.7</TargetFrameworkVersion>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug</OutputPath>
<DefineConstants>DEBUG;</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<ConsolePause>false</ConsolePause>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<Optimize>true</Optimize>
<OutputPath>bin\Release</OutputPath>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<ConsolePause>false</ConsolePause>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
</ItemGroup>
<ItemGroup>
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="JSONSpecial.cs" />
<Compile Include="JSONObject.cs" />
<Compile Include="JSONArray.cs" />
<Compile Include="JSONString.cs" />
<Compile Include="JSONNumber.cs" />
<Compile Include="JSONValue.cs" />
<Compile Include="JSONParser.cs" />
<Compile Include="mapping\JSONMapper.cs" />
<Compile Include="mapping\JSONMapping.cs" />
<Compile Include="mapping\JSONArrayMapping.cs" />
<Compile Include="mapping\JSONObjectMapping.cs" />
<Compile Include="mapping\JSONEnumerableMapping.cs" />
<Compile Include="mapping\JSONRPCCallMapping.cs" />
<Compile Include="mapping\JSONDateTimeMapping.cs" />
<Compile Include="mapping\JSONGuidMapping.cs" />
<Compile Include="mapping\JSONIPv4Mapping.cs" />
<Compile Include="mapping\JSONNetwork4Mapping.cs" />
<Compile Include="mapping\JSONTimeSpanMapping.cs" />
<Compile Include="mapping\JSONDateTimeOffsetMapping.cs" />
<Compile Include="mapping\JSONRPCResultMapping.cs" />
<Compile Include="attributes\JSONMappingAttribute.cs" />
<Compile Include="mapping\JSONEnumMapping.cs" />
<Compile Include="mapping\JSONDictionaryMapping.cs" />
<Compile Include="mapping\JSONExceptionMapping.cs" />
</ItemGroup>
<ItemGroup>
<Folder Include="mapping\" />
<Folder Include="attributes\" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\ln.types\ln.types.csproj">
<Project>{8D9AB9A5-E513-4BA7-A450-534F6456BF28}</Project>
<Name>ln.types</Name>
</ProjectReference>
</ItemGroup>
<Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
<ProjectExtensions>
<MonoDevelop>
<Properties>
<Policies>
<DotNetNamingPolicy ResourceNamePolicy="FileFormatDefault" DirectoryNamespaceAssociation="PrefixedHierarchical" />
</Policies>
</Properties>
</MonoDevelop>
</ProjectExtensions>
</Project>
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netcoreapp3.1</TargetFramework>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\ln.collections\ln.collections.csproj" />
<ProjectReference Include="..\ln.type\ln.type.csproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="System.Runtime" Version="4.3.1" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,26 @@
using System;
namespace ln.json.mapping
{
public class JSONByteArrayMapping : JSONMapping
{
public JSONByteArrayMapping()
: base(typeof(byte[]))
{
}
public override object FromJson(JSONMapper mapper, JSONValue json)
{
if (json is JSONString jString)
{
return Convert.FromBase64String(jString.Value);
}
throw new NotSupportedException();
}
public override JSONValue ToJson(JSONMapper mapper, object value)
{
return new JSONString(Convert.ToBase64String((byte[])value));
}
}
}

View File

@ -9,7 +9,7 @@
// **/
using System;
using ln.json;
using ln.types;
using ln.type;
namespace ln.json.mapping
{

View File

@ -1,25 +0,0 @@
using System;
using ln.types.net;
namespace ln.json.mapping
{
public class JSONIPv4Mapping : JSONMapping
{
public JSONIPv4Mapping() : base(typeof(IPv4))
{
}
public override object FromJson(JSONMapper mapper, JSONValue json)
{
if (json is JSONNumber)
{
return new IPv4((uint)(((JSONNumber)json).Decimal));
}
else
{
return IPv4.Parse(((JSONString)json).Value);
}
}
public override JSONValue ToJson(JSONMapper mapper, object value) => new JSONString(value.ToString());
}
}

View File

@ -0,0 +1,17 @@
using ln.type;
namespace ln.json.mapping
{
public class JSONIPv6Mapping : JSONMapping
{
public JSONIPv6Mapping() : base(typeof(IPv6))
{
}
public override object FromJson(JSONMapper mapper, JSONValue json)
{
return IPv6.Parse(((JSONString)json).Value);
}
public override JSONValue ToJson(JSONMapper mapper, object value) => new JSONString((value as IPv6).ToCIDR());
}
}

View File

@ -1,64 +1,291 @@
// /**
// * File: JSONMapper.cs
// * Author: haraldwolff
// *
// * This file and it's content is copyrighted by the Author and / or copyright holder.
// * Any use wihtout proper permission is illegal and may lead to legal actions.
// *
// *
// **/
using System;
using System.Reflection;
using System;
using System.Collections.Generic;
using System.Collections;
using System.Diagnostics.Tracing;
using System.Reflection;
using System.Text;
namespace ln.json.mapping
{
public delegate bool RequestCustomSerialization(object o, out JSONValue json);
public delegate bool RequestCustomUnserialization(JSONValue json, Type targetType, out object o);
public delegate bool RequestCustomMapping(Type targetType,out JSONMapping mapping);
public delegate bool MappingFactory(Type targetType, out JSONMapping mapping);
public class JSONMapper
{
public static JSONMapper DefaultMapper { get; set; } = new JSONMapper(true);
public static JSONMapper DefaultMapper { get; set; } = new JSONMapper();
public event RequestCustomSerialization OnRequestCustomSerialization;
public event RequestCustomUnserialization OnRequestCustomUnserialization;
public event RequestCustomMapping OnRequestCustomMapping;
public JSONObjectMappingFlags DefaultMappingFlags { get; set; } = JSONObjectMappingFlags.PROPERTIES | JSONObjectMappingFlags.FIELDS;
public BindingFlags DefaultBindingFlags { get; set; } = BindingFlags.Instance | BindingFlags.Public;
public bool RequestCustomSerialization(object o, out JSONValue json)
{
foreach (RequestCustomSerialization rcs in OnRequestCustomSerialization?.GetInvocationList() ?? new RequestCustomSerialization[0])
{
if (rcs(o, out json))
return true;
}
json = null;
return false;
}
public bool RequestCustomUnserialization(JSONValue json, Type targetType, out object o)
{
foreach (RequestCustomUnserialization rcu in OnRequestCustomUnserialization?.GetInvocationList() ?? new RequestCustomUnserialization[0])
{
if (rcu(json, targetType, out o))
return true;
}
o = null;
return false;
}
public bool RequestCustomMapping(Type targetType, out JSONMapping mapping)
{
foreach (RequestCustomMapping rcm in OnRequestCustomMapping?.GetInvocationList() ?? new RequestCustomMapping[0])
{
if (rcm(targetType, out mapping))
return true;
}
mapping = null;
return false;
}
Dictionary<Type, JSONMapping> mappings = new Dictionary<Type, JSONMapping>();
public virtual void Add(JSONMapping mapping) => mappings[mapping.TargetType] = mapping;
public JSONMapper()
Dictionary<Type, MappingFactory> mappingFactories = new Dictionary<Type, MappingFactory>();
public virtual void AddMappingFactory(Type targetType, MappingFactory mappingFactory) => mappingFactories.Add(targetType, mappingFactory);
public virtual bool GetOrBuildMapping(Type nativeType, out JSONMapping mapping) => TryGetMapping(nativeType, out mapping) || TryBuildRememberedMapping(nativeType, out mapping);
public virtual bool TryBuildRememberedMapping(Type nativeType,out JSONMapping mapping)
{
if (TryBuildMapping(nativeType, out mapping))
{
mappings.Add(nativeType, mapping);
return true;
}
return false;
}
private JSONMapper(bool defaultMapper)
public virtual bool TryBuildMapping(Type nativeType,out JSONMapping mapping)
{
/**
* Integer
**/
Add(new JSONMapping(
typeof(byte),
(JSONMapper arg1, object arg2) => new JSONNumber((int)arg2),
(JSONMapper arg1, JSONValue arg2) => Decimal.ToByte(((JSONNumber)arg2).Decimal)
));
Add(new JSONMapping(
if (nativeType.IsPrimitive)
{
mapping = null;
return false;
}
if (nativeType.IsArray)
{
mapping = new JSONArrayMapping(nativeType);
return true;
}
if (nativeType.IsSubclassOf(typeof(Exception)))
{
mapping = new JSONExceptionMapping(nativeType);
return true;
}
if ((mappingFactories.TryGetValue(nativeType, out MappingFactory mappingFactory)) && mappingFactory(nativeType, out mapping))
return true;
if (nativeType.IsGenericType)
{
Type genericTypeDefinition = nativeType.GetGenericTypeDefinition();
if (mappingFactories.TryGetValue(genericTypeDefinition, out mappingFactory) && mappingFactory(nativeType, out mapping))
return true;
if (genericTypeDefinition.Equals(typeof(IEnumerable<>)))
{
mapping = (JSONMapping)Activator.CreateInstance(typeof(JSONEnumerableMapping<>).MakeGenericType(nativeType.GetGenericArguments()[0]));
return true;
}
if (genericTypeDefinition.Equals(typeof(Dictionary<,>)))
{
mapping = (JSONMapping)Activator.CreateInstance(typeof(JSONDictionaryMapping<,>).MakeGenericType(nativeType.GetGenericArguments()));
return true;
}
}
mapping = new JSONObjectMapping(nativeType, DefaultMappingFlags, DefaultBindingFlags);
return true;
}
public virtual bool TryGetMapping(Type nativeType,out JSONMapping mapping)
{
if (mappings.TryGetValue(nativeType, out mapping))
return true;
if (RequestCustomMapping(nativeType, out mapping))
return true;
if ((this != DefaultMapper) && DefaultMapper.TryGetMapping(nativeType, out mapping))
return true;
return false;
}
public virtual bool Serialize(object o, out JSONValue json)
{
if (object.ReferenceEquals(null, o))
{
json = JSONNull.Instance;
return true;
}
Type type = o.GetType();
if (RequestCustomSerialization(o, out json))
return true;
if (TryGetMapping(type, out JSONMapping mapping))
{
json = mapping.ToJson(this, o);
return true;
}
if (type.IsEnum)
{
if (type.GetCustomAttribute<FlagsAttribute>() != null)
{
json = new JSONNumber((int)o);
}
else
{
json = new JSONString(Enum.GetName(type, o));
}
return true;
}
if (type.IsPrimitive)
{
throw new NotSupportedException(String.Format("JSONMapperBase: Unsupported primitive type found: {0}", type));
}
if (TryBuildRememberedMapping(type,out mapping))
{
json = mapping.ToJson(this, o);
return true;
}
return false;
}
public virtual bool Deserialize(JSONValue json, Type nativeType, out object o)
{
o = null;
if (JSONNull.Instance.Equals(json))
return true;
if (RequestCustomUnserialization(json, nativeType, out o))
return true;
if (TryGetMapping(nativeType, out JSONMapping mapping))
{
o = mapping.FromJson(this, json);
return true;
}
if (nativeType.IsEnum)
{
if (nativeType.GetCustomAttribute<FlagsAttribute>() != null)
{
o = Enum.ToObject(nativeType, (json as JSONNumber).AsInt);
}
else
{
o = Enum.Parse(nativeType, (json as JSONString).Value);
}
return true;
}
if (nativeType.IsPrimitive)
{
throw new NotSupportedException(string.Format("JSONMapperBase: Unsupported primitive type found: {0}", nativeType));
}
if (TryBuildRememberedMapping(nativeType, out mapping))
{
o = mapping.FromJson(this, json);
return true;
}
return false;
}
public void Apply(string jsonString, object o) => Apply((JSONObject)JSONParser.Parse(jsonString), o);
public virtual bool Apply(JSONObject json, object o)
{
Type nativeType = o.GetType();
if (TryGetMapping(nativeType,out JSONMapping mapping) || TryBuildRememberedMapping(nativeType, out mapping))
{
JSONObjectMapping objectMapping = mapping as JSONObjectMapping;
objectMapping.Apply(json, o);
return true;
}
return false;
}
public virtual JSONValue ToJson(object o)
{
if (Serialize(o,out JSONValue json))
return json;
throw new NotSupportedException();
}
public virtual T FromJson<T>(JSONValue json) => (T)FromJson(json, typeof(T));
public virtual object FromJson(JSONValue json,Type targetType)
{
if (Deserialize(json, targetType, out object o))
return o;
throw new NotSupportedException();
}
static JSONMapper()
{
DefaultMapper.Add(new JSONMapping(
typeof(byte),
(JSONMapper arg1, object arg2) => new JSONNumber((int)arg2),
(JSONMapper arg1, JSONValue arg2) => Decimal.ToByte(((JSONNumber)arg2).Decimal)
));
DefaultMapper.Add(new JSONMapping(
typeof(short),
(JSONMapper arg1, object arg2) => new JSONNumber((int)arg2),
(JSONMapper arg1, JSONValue arg2) => Decimal.ToInt16(((JSONNumber)arg2).Decimal)
));
Add(new JSONMapping(
DefaultMapper.Add(new JSONMapping(
typeof(int),
(JSONMapper arg1, object arg2) => new JSONNumber((int)arg2),
(JSONMapper arg1, JSONValue arg2) => Decimal.ToInt32(((JSONNumber)arg2).Decimal)
));
Add(new JSONMapping(
DefaultMapper.Add(new JSONMapping(
typeof(long),
(JSONMapper arg1, object arg2) => new JSONNumber((long)arg2),
(JSONMapper arg1, JSONValue arg2) => Decimal.ToInt64(((JSONNumber)arg2).Decimal)
));
Add(new JSONMapping(
DefaultMapper.Add(new JSONMapping(
typeof(ushort),
(JSONMapper arg1, object arg2) => new JSONNumber((uint)arg2),
(JSONMapper arg1, JSONValue arg2) => Decimal.ToUInt16(((JSONNumber)arg2).Decimal)
));
Add(new JSONMapping(
DefaultMapper.Add(new JSONMapping(
typeof(uint),
(JSONMapper arg1, object arg2) => new JSONNumber((uint)arg2),
(JSONMapper arg1, JSONValue arg2) => Decimal.ToUInt32(((JSONNumber)arg2).Decimal)
));
Add(new JSONMapping(
DefaultMapper.Add(new JSONMapping(
typeof(ulong),
(JSONMapper arg1, object arg2) => new JSONNumber((ulong)arg2),
(JSONMapper arg1, JSONValue arg2) => Decimal.ToUInt64(((JSONNumber)arg2).Decimal)
@ -67,12 +294,12 @@ namespace ln.json.mapping
/**
* Float
**/
Add(new JSONMapping(
DefaultMapper.Add(new JSONMapping(
typeof(float),
(JSONMapper arg1, object arg2) => new JSONNumber((float)arg2),
(JSONMapper arg1, JSONValue arg2) => (float)Decimal.ToDouble(((JSONNumber)arg2).Decimal)
));
Add(new JSONMapping(
DefaultMapper.Add(new JSONMapping(
typeof(double),
(JSONMapper arg1, object arg2) => new JSONNumber((double)arg2),
(JSONMapper arg1, JSONValue arg2) => Decimal.ToDouble(((JSONNumber)arg2).Decimal)
@ -82,7 +309,7 @@ namespace ln.json.mapping
* Strings
**/
Add(new JSONMapping(
DefaultMapper.Add(new JSONMapping(
typeof(string),
(JSONMapper arg1, object arg2) => new JSONString((string)arg2),
(JSONMapper arg1, JSONValue arg2) => ((JSONString)arg2).Value
@ -92,102 +319,27 @@ namespace ln.json.mapping
* Others
**/
Add(new JSONMapping(
DefaultMapper.Add(new JSONMapping(
typeof(char),
(JSONMapper arg1, object arg2) => new JSONString(new String(new char[] { (char)arg2 })),
(JSONMapper arg1, JSONValue arg2) => ((JSONString)arg2).Value[0]
));
DefaultMapper.Add(new JSONMapping(
typeof(bool),
(JSONMapper arg1, object arg2) => ((bool)arg2) ? (JSONValue)JSONTrue.Instance : (JSONValue)JSONFalse.Instance,
(JSONMapper arg1, JSONValue arg2) => (arg2.ValueType == JSONValueType.TRUE) || (arg2.ValueType == JSONValueType.FALSE) ? false : throw new NotSupportedException()
));
Add(new JSONDateTimeMapping());
Add(new JSONDateTimeOffsetMapping());
Add(new JSONGuidMapping());
Add(new JSONIPv4Mapping());
Add(new JSONNetwork4Mapping());
Add(new JSONTimeSpanMapping());
DefaultMapper.Add(new JSONByteArrayMapping());
Add(new JSONRPCCallMapping());
Add(new JSONRPCResultMapping());
DefaultMapper.Add(new JSONDateTimeMapping());
DefaultMapper.Add(new JSONDateTimeOffsetMapping());
DefaultMapper.Add(new JSONGuidMapping());
DefaultMapper.Add(new JSONTimeSpanMapping());
DefaultMapper.Add(new JSONRPCCallMapping());
DefaultMapper.Add(new JSONRPCResultMapping());
}
public void Add(JSONMapping mapping)
{
mappings[mapping.TargetType] = mapping;
}
private JSONMapping FindMapping(Type targetType)
{
if (mappings.ContainsKey(targetType))
return mappings[targetType];
if (this != DefaultMapper)
return DefaultMapper.FindMapping(targetType);
if (!targetType.IsPrimitive)
{
if (targetType.IsArray)
{
Add(new JSONArrayMapping(targetType));
}
else if (targetType.IsEnum)
{
Add(new JSONEnumMapping(targetType));
}
else if (targetType.IsSubclassOf(typeof(Exception)))
{
Add(new JSONExceptionMapping(targetType));
}
else if (targetType.IsGenericType)
{
Type genericTypeDefinition = targetType.GetGenericTypeDefinition();
if (genericTypeDefinition.Equals(typeof(IEnumerable<>)))
{
Add((JSONMapping)Activator.CreateInstance(typeof(JSONEnumerableMapping<>).MakeGenericType(targetType.GetGenericArguments()[0])));
}
else if (genericTypeDefinition.Equals(typeof(Dictionary<,>)))
{
Add((JSONMapping)Activator.CreateInstance(typeof(JSONDictionaryMapping<,>).MakeGenericType(targetType.GetGenericArguments())));
}
}
else
{
Add(new JSONObjectMapping(targetType));
}
return mappings[targetType];
}
throw new NotSupportedException(targetType.ToString());
}
public T FromJson<T>(string jsonString) => FromJson<T>((JSONObject)JSONParser.Parse(jsonString));
public T FromJson<T>(JSONValue json) => (T)FromJson(json, typeof(T));
public object FromJson(string jsonString, Type targetType) => FromJson((JSONObject)JSONParser.Parse(jsonString), targetType);
public object FromJson(JSONValue json, Type targetType)
{
if (json.ValueType == JSONValueType.NULL)
return null;
return FindMapping(targetType).FromJson(this, json);
}
public JSONValue ToJson(object value)
{
if (value == null)
return JSONNull.Instance;
Type sourceType = value.GetType();
return FindMapping(sourceType).ToJson(this, value);
}
public void Apply(string jsonString, object o) => Apply((JSONObject)JSONParser.Parse(jsonString), o);
public void Apply(JSONObject json,object o)
{
JSONMapping mapping = FindMapping(o.GetType());
if (!(mapping is JSONObjectMapping))
throw new NotSupportedException();
JSONObjectMapping objectMapping = mapping as JSONObjectMapping;
objectMapping.Apply(this, json, o);
}
}
}

View File

@ -1,15 +0,0 @@
using System;
using ln.types.net;
namespace ln.json.mapping
{
public class JSONNetwork4Mapping : JSONMapping
{
public JSONNetwork4Mapping() : base(typeof(Network4))
{
}
public override object FromJson(JSONMapper mapper, JSONValue json) => Network4.Parse(((JSONString) json).Value);
public override JSONValue ToJson(JSONMapper mapper, object value) => new JSONString(((Network4)value).ToString());
}
}

View File

@ -18,6 +18,8 @@ namespace ln.json.mapping
void Apply(JSONObject json);
}
public enum JSONObjectMappingFlags { NONE, FIELDS, PROPERTIES }
public class JSONObjectMapping : JSONMapping
{
Dictionary<string, Action<object,object>> setters = new Dictionary<string, Action<object,object>>();
@ -25,28 +27,36 @@ namespace ln.json.mapping
Dictionary<string, Type> types = new Dictionary<string, Type>();
public JSONObjectMapping(Type type)
: this(type, JSONObjectMappingFlags.FIELDS | JSONObjectMappingFlags.PROPERTIES, BindingFlags.Instance | BindingFlags.Public)
{ }
public JSONObjectMapping(Type type, JSONObjectMappingFlags mappingFlags)
: this(type, mappingFlags, BindingFlags.Instance | BindingFlags.Public)
{ }
public JSONObjectMapping(Type type,JSONObjectMappingFlags mappingFlags, BindingFlags bindingFlags)
: base(type)
{
foreach (FieldInfo fieldInfo in type.GetFields(BindingFlags.Instance | BindingFlags.Public))
{
JSONMappingAttribute mappingAttribute = fieldInfo.GetCustomAttribute<JSONMappingAttribute>();
if ((mappingAttribute == null) || !mappingAttribute.Private)
if ((mappingFlags & JSONObjectMappingFlags.FIELDS) == JSONObjectMappingFlags.FIELDS)
foreach (FieldInfo fieldInfo in type.GetFields(bindingFlags))
{
setters.Add(fieldInfo.Name, (object arg1, object arg2) => fieldInfo.SetValue(arg1, arg2));
getters.Add(fieldInfo.Name, (object arg) => fieldInfo.GetValue(arg));
types.Add(fieldInfo.Name, fieldInfo.FieldType);
JSONMappingAttribute mappingAttribute = fieldInfo.GetCustomAttribute<JSONMappingAttribute>();
if ((mappingAttribute == null) || !mappingAttribute.Private)
{
setters.Add(fieldInfo.Name, (object arg1, object arg2) => fieldInfo.SetValue(arg1, arg2));
getters.Add(fieldInfo.Name, (object arg) => fieldInfo.GetValue(arg));
types.Add(fieldInfo.Name, fieldInfo.FieldType);
}
}
}
foreach (PropertyInfo propertyInfo in type.GetProperties(BindingFlags.Instance | BindingFlags.Public))
{
JSONMappingAttribute mappingAttribute = propertyInfo.GetCustomAttribute<JSONMappingAttribute>();
if ((propertyInfo.GetIndexParameters().Length == 0) && ((mappingAttribute == null) || !mappingAttribute.Private))
if ((mappingFlags & JSONObjectMappingFlags.PROPERTIES) == JSONObjectMappingFlags.PROPERTIES)
foreach (PropertyInfo propertyInfo in type.GetProperties(bindingFlags))
{
setters.Add(propertyInfo.Name, (object arg1, object arg2) => propertyInfo.SetValue(arg1, arg2));
getters.Add(propertyInfo.Name, (object arg) => propertyInfo.GetValue(arg));
types.Add(propertyInfo.Name, propertyInfo.PropertyType);
JSONMappingAttribute mappingAttribute = propertyInfo.GetCustomAttribute<JSONMappingAttribute>();
if ((propertyInfo.GetIndexParameters().Length == 0) && ((mappingAttribute == null) || !mappingAttribute.Private))
{
setters.Add(propertyInfo.Name, (object arg1, object arg2) => { if (propertyInfo.CanWrite) propertyInfo.SetValue(arg1, arg2); });
getters.Add(propertyInfo.Name, (object arg) => propertyInfo.GetValue(arg));
types.Add(propertyInfo.Name, propertyInfo.PropertyType);
}
}
}
}
public override object FromJson(JSONMapper mapper, JSONValue json)

View File

@ -1,5 +1,5 @@
using System;
using ln.types.rpc;
using ln.type.rpc;
namespace ln.json.mapping
{

View File

@ -1,5 +1,4 @@
using System;
using ln.types.rpc;
using ln.type.rpc;
namespace ln.json.mapping
{
public class JSONRPCResultMapping : JSONMapping

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -1,7 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup Condition=" '$(RunConfiguration)' == 'Default' ">
<StartAction>Project</StartAction>
<ConsolePause>true</ConsolePause>
</PropertyGroup>
</Project>

View File

@ -1,35 +0,0 @@
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ln.json", "ln.json.csproj", "{D9342117-3249-4D8B-87C9-51A50676B158}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "json.test", "json.test\json.test.csproj", "{49FFBD9F-655E-4C74-A078-99B5E09059C6}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ln.types", "ln.types\ln.types.csproj", "{8D9AB9A5-E513-4BA7-A450-534F6456BF28}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ln.logging", "ln.logging\ln.logging.csproj", "{D471A566-9FB6-41B2-A777-3C32874ECD0E}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{D9342117-3249-4D8B-87C9-51A50676B158}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{D9342117-3249-4D8B-87C9-51A50676B158}.Debug|Any CPU.Build.0 = Debug|Any CPU
{D9342117-3249-4D8B-87C9-51A50676B158}.Release|Any CPU.ActiveCfg = Release|Any CPU
{D9342117-3249-4D8B-87C9-51A50676B158}.Release|Any CPU.Build.0 = Release|Any CPU
{49FFBD9F-655E-4C74-A078-99B5E09059C6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{49FFBD9F-655E-4C74-A078-99B5E09059C6}.Debug|Any CPU.Build.0 = Debug|Any CPU
{49FFBD9F-655E-4C74-A078-99B5E09059C6}.Release|Any CPU.ActiveCfg = Release|Any CPU
{49FFBD9F-655E-4C74-A078-99B5E09059C6}.Release|Any CPU.Build.0 = Release|Any CPU
{8D9AB9A5-E513-4BA7-A450-534F6456BF28}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{8D9AB9A5-E513-4BA7-A450-534F6456BF28}.Debug|Any CPU.Build.0 = Debug|Any CPU
{8D9AB9A5-E513-4BA7-A450-534F6456BF28}.Release|Any CPU.ActiveCfg = Release|Any CPU
{8D9AB9A5-E513-4BA7-A450-534F6456BF28}.Release|Any CPU.Build.0 = Release|Any CPU
{D471A566-9FB6-41B2-A777-3C32874ECD0E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{D471A566-9FB6-41B2-A777-3C32874ECD0E}.Debug|Any CPU.Build.0 = Debug|Any CPU
{D471A566-9FB6-41B2-A777-3C32874ECD0E}.Release|Any CPU.ActiveCfg = Release|Any CPU
{D471A566-9FB6-41B2-A777-3C32874ECD0E}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
EndGlobal