Parsing a JSON string for a .NET object

I am parsing a JSON string in the corresponding .NET object using the Newtonsoft library. I have a problem parsing JSON properties that are arrays. Sometimes the JSON property is an array, at other times it is one element.

Example:

This is a .NET object:

  public class xx
  {
      public string yy { get; set; }       
      public List<string> mm{ get; set; }        
  }

When I get this JSON:

{ "xx": {"yy":"nn", "mm": [ "zzz", "aaa" ] } }

I know how to:

JsonConvert.DeserializeObject<xx>(json);

But sometimes I get this JSON:

{ "xx": {"yy":"nn", "mm":"zzz"} }

And deserialization is not performed due to the list property on the C # object.

How can I define an object to deserialize two JSON strings in the same object (c List<string>).

-------- UPDATE -----

First of all, WS generates XML that performs some operation. XML is like

<xx yy='nn'><mm>zzz</mm></xx>

and if there are more elements:

<xx yy='nn'><mm>zzz</mm><mm>aaa</mm></xx>

Finally, WS converts this XML:

XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);           
var json = JsonConvert.SerializeXmlNode(doc); 

and send me json .. and here my problem begins ..

+5
4

:

, JSON.Net XML, , , , , , . XML DOM , , , .

, SerializeGroupedNodes() SerializeNode() .

XmlNodeConverter.cs @CodePlex, ChangeSet # 63616

, , , , , .

Json.Net , JsonConverter, .

, . , , , XML JSON.

, , , . , , JsonAttribute (MMArrayConverter), . , , , , , , , IList<string> - Lazy<List<string>> .

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Converters;

namespace JsonArrayImplictConvertTest
{
    public class MMArrayConverter : JsonConverter
    {
        public override bool CanConvert(Type objectType)
        {
            return objectType.Equals(typeof(List<string>));
        }

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            if (reader.TokenType == JsonToken.StartArray)
            {
                List<string> parseList = new List<string>();
                do
                {
                    if (reader.Read())
                    {
                        if (reader.TokenType == JsonToken.String)
                        {
                            parseList.Add((string)reader.Value);
                        }
                        else
                        {
                            if (reader.TokenType == JsonToken.Null)
                            {
                                parseList.Add(null);
                            }
                            else
                            {
                                if (reader.TokenType != JsonToken.EndArray)
                                {
                                    throw new ArgumentException(string.Format("Expected String/Null, Found JSON Token Type {0} instead", reader.TokenType.ToString()));
                                }
                            }
                        }
                    }
                    else
                    {
                        throw new InvalidOperationException("Broken JSON Input Detected");
                    }
                }
                while (reader.TokenType != JsonToken.EndArray);

                return parseList;
            }

            if (reader.TokenType == JsonToken.Null)
            {
                // TODO: You need to decide here if we want to return an empty list, or null.
                return null;
            }

            if (reader.TokenType == JsonToken.String)
            {
                List<string> singleList = new List<string>();
                singleList.Add((string)reader.Value);
                return singleList;
            }

            throw new InvalidOperationException("Unhandled case for MMArrayConverter. Check to see if this converter has been applied to the wrong serialization type.");
        }

        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            // Not implemented for brevity, but you could add this if needed.
            throw new NotImplementedException();
        }
    }

    public class ModifiedXX
    {
        public string yy { get; set; }

        [JsonConverter(typeof(MMArrayConverter))]
        public List<string> mm { get; set; }

        public void Display()
        {
            Console.WriteLine("yy is {0}", this.yy);
            if (null == mm)
            {
                Console.WriteLine("mm is null");
            }
            else
            {
                Console.WriteLine("mm contains these items:");
                mm.ForEach((item) => { Console.WriteLine("  {0}", item); });
            }
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            string jsonTest1 = "{\"yy\":\"nn\", \"mm\": [ \"zzz\", \"aaa\" ] }";
            ModifiedXX obj1 = JsonConvert.DeserializeObject<ModifiedXX>(jsonTest1);
            obj1.Display();

            string jsonTest2 = "{\"yy\":\"nn\", \"mm\": \"zzz\" }";
            ModifiedXX obj2 = JsonConvert.DeserializeObject<ModifiedXX>(jsonTest2);
            obj2.Display();

            // This test is now required in case we messed up the parser state in our converter.
            string jsonTest3 = "[{\"yy\":\"nn\", \"mm\": [ \"zzz\", \"aaa\" ] },{\"yy\":\"nn\", \"mm\": \"zzz\" }]";
            List<ModifiedXX> obj3 = JsonConvert.DeserializeObject<List<ModifiedXX>>(jsonTest3);
            obj3.ForEach((obj) => { obj.Display(); });

            Console.ReadKey();
        }
    }
}

:

JSON, , . , , , XML JSON, .

, , , - , , mm object, , JSON.Net Linq. , mm object , null, a string JArray mm DeserializeObject<>.

, . , JObject, . , - mmAsList() . , null , null List<string>; , , .

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace JsonArrayUnionTest
{
    public class ModifiedXX
    {
        public string yy { get; set; }
        public object mm { get; set; }

        public List<string> mmAsList()
        {
            if (null == mm) { return null; }
            if (mm is JArray)
            {
                JArray mmArray = (JArray)mm;
                return mmArray.Values<string>().ToList();
            }

            if (mm is JObject)
            {
                JObject mmObj = (JObject)mm;
                if (mmObj.Type == JTokenType.String)
                {
                    return MakeList(mmObj.Value<string>());
                }
            }

            if (mm is string)
            {
                return MakeList((string)mm);
            }

            throw new ArgumentOutOfRangeException("unhandled case for serialized value for mm (cannot be converted to List<string>)");
        }

        protected List<string> MakeList(string src)
        {
            List<string> newList = new List<string>();
            newList.Add(src);
            return newList;
        }

        public void Display()
        {
            Console.WriteLine("yy is {0}", this.yy);
            List<string> mmItems = mmAsList();
            if (null == mmItems)
            {
                Console.WriteLine("mm is null");
            }
            else
            {
                Console.WriteLine("mm contains these items:");
                mmItems.ForEach((item) => { Console.WriteLine("  {0}", item); });
            }
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            string jsonTest1 = "{\"yy\":\"nn\", \"mm\": [ \"zzz\", \"aaa\" ] }";
            ModifiedXX obj1 = JsonConvert.DeserializeObject<ModifiedXX>(jsonTest1);
            obj1.Display();

            string jsonTest2 = "{\"yy\":\"nn\", \"mm\": \"zzz\" }";
            ModifiedXX obj2 = JsonConvert.DeserializeObject<ModifiedXX>(jsonTest2);
            obj2.Display();

            Console.ReadKey();
        }
    }
}
+5

, . , , , , , , - . , , , , .

object someValue;
try
{
   someValue =JsonConvert.DeserializeObject<TypeWithList>(json);
}
catch
{
    try
    {
      someValue = JsonConvert.DeserializeObject<TypeWithString>(json);
    }
    catch
    {
    //Darn, yet another type
    }
}
+1

JsonConvert

PopulateObject ( , , JsonSerializerSettings);

JsonSerializerSettings

new JsonSerializerSettings(){TypeNameHandling = TypeNameHandling.All})
0

, Javascript. , JSON, .

var stringProperty = new String();
var arrayProperty = new Array();

// Assign value to stringProperty and push elements into arrayProperty

var object = {
    stringProperty: stringProperty,
    arrayProperty: arrayProperty
};

var jsonObject = JSON.stringify(object);

document.write(jsonObject);

, , arrayProperty , , .

-2

All Articles