M
M
Maxim2017-04-27 20:34:01
JSON
Maxim, 2017-04-27 20:34:01

JSON deserialization control?

How to manage deserialization?
There is a class

[DataContract]
class A
{
  [DataMember]
  public Int32 P1 { get; private set; }
  [DataMember]
  public String P2 { get; private set; }
}

json
{
  "serializable": true, // этого поля нет в классе
  "P1": 1,
  "P2": "ffda"
}

How to deserialize objects only with "serializable": true and set false to null or do something else (take a new one)?
How to deserialize derivatives of A with additional members?
PS, Each object is in a separate file

Answer the question

In order to leave comments, you need to log in

2 answer(s)
F
FreeBa, 2017-04-27
@Got_Oxidus

Something like this:

using Newtonsoft.Json;
using System;
using System.Collections.Generic;

namespace ConsoleApplication11
{
    class Test
    {
        public string P1 { get; set; }
        public int P2 { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            var str = JsonConvert.SerializeObject(new List<object> {
                new { s = true, P1 = "one", P2 = 12 },
                new { s = false, P1 = "two", P2 = 13 },
                new { s = true, P1 = "three", P2 = 14 } });

            dynamic dObject = JsonConvert.DeserializeObject(str);

            var list = new List<Test>();

            foreach (var item in dObject)
            {
                if (item.s == true)
                {
                    list.Add(item.ToObject<Test>());
                }
                else
                {
                    Console.WriteLine("No way");
                }
            }

            Console.ReadKey();
        }
    }
}

Although if you need to filter before translation into the object model, then this will have to be done manually.

J
John_Nash, 2017-04-27
@John_Nash

1) write your own implementation of the deserializer; or write a class with one serializable field, get the result from it and then decide what to do
2) just like the base one

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question