Esempio n. 1
0
        public void Deserialize_BadJson_Throws()
        {
            var    json   = @"
{ 
    'instanceId':'localhost:foo',
    'hostName':'localhost',
    'app':'FOO',
    'ipAddr':'192.168.56.1',
    
";
            Stream stream = TestHelpers.StringToStream(json);
            var    ex     = Assert.Throws <JsonSerializationException>(() => JsonSerialization.Deserialize <JsonInstanceInfo>(stream));
        }
Esempio n. 2
0
        public void serialize_fixtures()
        {
            var library = FixtureLibrary.CreateForAppDomain(CellHandling.Basic());

            // CreateLocation
            // AddressVerification

            var fixtureModels = library.Models.GetAll().ToArray();

            var json = JsonSerialization.ToJson(fixtureModels);

            var models = JsonSerialization.Deserialize <FixtureModel[]>(json);

            models.Each(x => Debug.WriteLine(x.key));
        }
Esempio n. 3
0
        public void round_trip_serialization()
        {
            theResult.MarkMatched("1");
            theResult.MarkExtra(new StepValues("foo"));
            theResult.MarkMissing("bar");
            theResult.MarkWrongOrder(Guid.NewGuid().ToString(), 1);

            var json = JsonSerialization.ToJson(theResult);

            var newResult = JsonSerialization.Deserialize <SetVerificationResult>(json);

            newResult.matches.Single().ShouldBe("1");
            newResult.extras.Count().ShouldBe(1);
            newResult.missing.Single().ShouldBe("bar");
            newResult.wrongOrdered.Count().ShouldBe(1);
        }
Esempio n. 4
0
        internal static Project Open(FileInfo projectFile)
        {
            var project = new Project
            {
                Settings = JsonSerialization.Deserialize <ProjectSettings>(projectFile.FullName)
            };

            project.Guid = new Guid(projectFile.ToAssetGuid());

            // Patch up any guid references if they are missing.
            if (Guid.Empty == project.Settings.Configuration)
            {
                project.Settings.Configuration = new Guid(AssetDatabaseUtility.GetAssetGuid(projectFile.ChangeExtension(k_ConfigurationFileExtension)));
            }

            if (Guid.Empty == project.Settings.MainAsmdef)
            {
                project.Settings.MainAsmdef = new Guid(AssetDatabaseUtility.GetAssetGuid(projectFile.ChangeExtension(k_AssemblyDefinitionFileExtension)));
            }

            if (!DomainReload.IsDomainReloading)
            {
                var entityManager = project.EntityManager;
                var configFile    = project.GetConfigurationFile();

                if (configFile.Exists)
                {
                    project.PersistenceManager.LoadScene(entityManager, configFile.FullName);

                    // Hack: remove scene guid/instance id
                    var configEntity = project.WorldManager.GetConfigEntity();
                    entityManager.RemoveComponent <SceneGuid>(configEntity);
                    entityManager.RemoveComponent <SceneInstanceId>(configEntity);
                }
                else
                {
                    var configEntity = project.WorldManager.CreateEntity(project.ArchetypeManager.Config);
                    entityManager.SetComponentData(configEntity, DisplayInfo.Default);
                }
            }

            s_Projects.Add(project);
            ProjectOpened(project);

            DomainCache.CacheIncludedAssemblies(project);
            return(project);
        }
        public void SerializeDeserializeTestPersonProper()
        {
            var person = RandomData.GenerateRefPerson <PersonProper>();

            //Serialize
            var json = JsonSerialization.Serialize(person);

            //For debugging
            //JsonSerialization.SerializeToFile(person, @"C:\dotNetTips.com\DebugOutput\PersonProper.json");

            Assert.IsTrue(string.IsNullOrEmpty(json) is false);

            //Deserialize
            var serializedPerson = JsonSerialization.Deserialize <PersonProper>(Resources.JsonPersonProper);

            Assert.IsNotNull(serializedPerson);
        }
Esempio n. 6
0
        private IDictionary <string, EmbeddedSpec> readSpecs()
        {
            var dict = new Dictionary <string, EmbeddedSpec>();

            var fileSystem = new FileSystem();

            fileSystem.FindFiles(_settings.Root, FileSet.Deep("*.specs.json")).Each(file =>
            {
                var json     = fileSystem.ReadStringFromFile(file);
                var response = JsonSerialization.Deserialize <BatchRunResponse>(json);
                var fixtures = new Dictionary <string, FixtureModel>();
                response.fixtures.Each(x => fixtures.Add(x.key, x));

                response.records.Each(rec => dict.Add(rec.specification.path, new EmbeddedSpec(fixtures, rec)));
            });

            return(dict);
        }
Esempio n. 7
0
            public void LoadSettings(string serial)
            {
                try
                {
                    string  json = File.ReadAllText(FilePath);
                    dynamic data = JsonSerialization.Deserialize(json);
                    DeviceName = (string)data.deviceName;
                }
                catch
                {
                }

                if (String.IsNullOrWhiteSpace(DeviceName))
                {
                    DeviceName = serial.ToUpper();
                    SaveSettings();
                }
            }
Esempio n. 8
0
        public static async Task <EventsData> LoadEvensAsync(this IDynamoDBContext connection, Guid correlationId, IEnumerable <Type> knownTypes, DynamoDBOperationConfig configuration)
        {
            var data = await GetEventsAsync(connection, correlationId, configuration);

            var events = new List <object>();

            if (data is null)
            {
                return new EventsData {
                           Events = events, LastVersion = null
                }
            }
            ;

            events.AddRange(data.Events.SelectMany(@event => JsonSerialization.Deserialize(@event, knownTypes)));
            return(new EventsData {
                Events = events, LastVersion = data.Version
            });
        }
        public static async Task <AggregatedEvents> LoadEventsAsync(this IDynamoDBContext context, Guid aggregateId, IEnumerable <Type> knownTypes, DynamoDbEventStoreOptions options)
        {
            var data = await context.GetEventsAsync(aggregateId, options);

            var events = new List <object>();

            if (data is null)
            {
                return new AggregatedEvents {
                           Events = events, LastVersion = null
                }
            }
            ;

            events.AddRange(data.SelectMany(@event => JsonSerialization.Deserialize(@event, knownTypes)));
            return(new AggregatedEvents {
                Events = events, LastVersion = data.Max(model => model.Version), AggregateId = aggregateId.ToString()
            });
        }
Esempio n. 10
0
        public static DatabaseSettings GetDatabaseSettings()
        {
            DatabaseSettings settings;
            var jsonString = UnityEditor.EditorPrefs.GetString(EditorPrefsKey);

            if (!String.IsNullOrEmpty(jsonString))
            {
                settings = (DatabaseSettings)JsonSerialization.Deserialize(typeof(DatabaseSettings), jsonString);
            }
            else
            {
                settings                 = ScriptableObject.CreateInstance <DatabaseSettings>();
                settings.liveReload      = true;
                settings.databaseFolder  = DefaultFolder;
                settings.databaseName    = DefaultName;
                settings.savePath        = DefaultPath;
                settings.ViewingDatabase = DefaultName;
            }

            return(settings);
        }
Esempio n. 11
0
            public static PacketData FromJson(string json)
            {
                dynamic  data         = JsonSerialization.Deserialize(json);
                string   serial       = (string)data.serial;
                string   name         = (string)data.name;
                string   version      = (string)data.version;
                int      httpPort     = (int)data.httpPort;
                TimeSpan runningTime  = TimeSpan.FromSeconds((int)data.runningSecs);
                string   serviceState = (string)data.serviceState ?? "Unknown";

                List <Interface> interfaces = new List <Interface>();

                foreach (dynamic i in data.interfaces)
                {
                    string iName     = (string)i.name;
                    string iPhysical = (string)i.physical;
                    string iInternat = (string)i.internet;
                    interfaces.Add(new Interface(iName, iPhysical, iInternat));
                }

                return(new PacketData(serial, name, version, httpPort, runningTime, serviceState, interfaces));
            }
Esempio n. 12
0
        /// <summary>
        /// Loads entries file.
        /// </summary>
        private static List <Entry> LoadEntriesFile()
        {
            try
            {
                if (!File.Exists(EntriesFile))
                {
                    Console.WriteLine($"Entries file {EntriesFile} does not exist");
                    Console.Write("Continue and create a new one? [Y/N] : ");
                    string input = Console.ReadLine().Trim().ToUpper();
                    if (input != "Y")
                    {
                        throw new Exception("Quitting program");
                    }
                    return(new List <Entry>());
                }

                Console.WriteLine($"Loading file {EntriesFile}");
                string  json = File.ReadAllText(EntriesFile);
                dynamic data = JsonSerialization.Deserialize(json);

                List <Entry> entries = new List <Entry>();
                foreach (dynamic e in data.entries)
                {
                    string ip   = (string)e.ip;
                    string host = (string)e.host;
                    string mac  = (string)e.mac;
                    entries.Add(new Entry(ip, host, mac));
                }
                entries = entries.OrderBy(e => e.SortIP).ToList();
                return(entries);
            }
            catch (Exception ex)
            {
                throw new Exception($"Unable to load file {EntriesFile}", ex);
            }
        }
 public static TResult FromJson <TResult>([NotNull] this string json)
 {
     return(JsonSerialization.Deserialize <TResult>(json.ArgumentNotNullOrEmpty()));
 }
Esempio n. 14
0
 protected JObject Decode(byte[] message)
 => JsonSerialization.Deserialize(Encoding.UTF8.GetString(message));
Esempio n. 15
0
        /// <summary>
        /// Clone using JSON, can just use CreateInstance<>()?
        /// </summary>
        /// <returns>The cloned Template</returns>
        public Template Clone()
        {
            string json = JsonSerialization.Serialize(this.GetType(), this);

            return((Template)JsonSerialization.Deserialize(this.GetType(), json));
        }
        public void HandleJson(string json, IApplication app)
        {
            var message = JsonSerialization.Deserialize <T>(json);

            HandleMessage(message, app);
        }
        public void Deserialize04()
        {
            var result = JsonSerialization.Deserialize <PersonRecord>(Resources.PersonProperJson);

            base.Consumer.Consume(result);
        }
Esempio n. 18
0
        private void Export(AssetInfo asset, Entity entity, BuildPipeline.BuildContext context)
        {
            // Get asset exporter
            var assetExporter = m_AssetExporters.Values.FirstOrDefault(x => x.CanExport(asset.Object));

            if (assetExporter == null)
            {
                return; // Assets without asset exporter do not need to export anything
            }

            // Get asset path
            var assetPath = UnityEditor.AssetDatabase.GetAssetPath(asset.Object);

            if (string.IsNullOrEmpty(assetPath))
            {
                assetPath = string.Empty;
            }

            // Compute asset export file path
            Assert.IsTrue(EntityManager.HasComponent <EntityGuid>(entity));
            var assetGuid  = WorldManager.GetEntityGuid(entity);
            var outputFile = context.DataDirectory.GetFile(assetGuid.ToString("N"));

            // Compute asset export hash
            var exportHash = assetExporter.GetExportHash(asset.Object);

            if (exportHash == Guid.Empty)
            {
                throw new InvalidOperationException($"{assetExporter.GetType().FullName} did not provide a valid asset export hash.");
            }

            // Retrieve exported files from manifest
            IEnumerable <FileInfo> exportedFiles = null;
            var manifestFile = new FileInfo(outputFile.FullName + ".manifest");

            if (manifestFile.Exists)
            {
                try
                {
                    var manifest = JsonSerialization.Deserialize <BuildManifest.Entry>(manifestFile.FullName);
                    if (manifest != null &&
                        manifest.AssetPath == assetPath &&
                        manifest.AssetGuid == assetGuid &&
                        manifest.ExportVersion == assetExporter.ExportVersion &&
                        manifest.ExportHash == exportHash)
                    {
                        // Verify that all files exists
                        var files = manifest.ExportedFiles.Select(x => new FileInfo(x));
                        if (files.Where(file => file.Exists).Count() == manifest.ExportedFiles.Count)
                        {
                            exportedFiles = files;
                        }
                    }
                }
                catch (InvalidJsonException)
                {
                    // Manifest file couldn't be read, format might have changed
                }
            }

            // Export asset if export files are not found
            var didExport = false;

            if (exportedFiles == null)
            {
                exportedFiles = assetExporter.Export(outputFile, asset.Object);
                didExport     = exportedFiles != null && exportedFiles.Count() > 0;
            }

            // Update manifest
            var entry = context.Manifest.Add(assetGuid, assetPath, exportedFiles, assetExporter.ExportVersion, exportHash);

            if (entry != null && didExport)
            {
                manifestFile.WriteAllText(JsonSerialization.Serialize(entry));
            }
        }
Esempio n. 19
0
        public void HandleJson(string json)
        {
            var message = JsonSerialization.Deserialize <T>(json);

            HandleMessage(message);
        }
Esempio n. 20
0
 /// <summary>
 /// Load Database From a Text Asset
 /// </summary>
 /// <param name="json"></param>
 /// <returns></returns>
 public static Database Load(TextAsset json)
 {
     return((Database)JsonSerialization.Deserialize(typeof(Database), json.text));
 }
Esempio n. 21
0
 /// <summary>
 /// 将JSON字符串反序列化为对象
 /// </summary>
 /// <typeparam name="T"></typeparam>
 /// <param name="jsonString"></param>
 /// <returns></returns>
 public static T ToJsonObject <T>(this string jsonString)
 {
     return(JsonSerialization.Deserialize <T>(jsonString));
 }