2016-11-05 19 views
1

让说我有一个来自同一AJAX调用根据传入的参数返回以下2个JSON对象可与2种不同的数据类型,同一属性的JSON对象以相同的反序列化调用反序列化?

第一个返回的孩子属性的字符串数组:

{ 
    parent: { 
     child: [ 
      "item 1", 
      "item 2", 
      "item 3", 
     ] 
    } 
} 

,第二个用于返回属性的对象数组:

{ 
    parent: { 
     child: [ 
      { 
       "attribute1": "Attribute 1", 
       "attribute2": "Attribute 2", 
       "attribute3": "Attribute 3" 
      }, 
      { 
       "attribute1": "Attribute 1", 
       "attribute2": "Attribute 2", 
       "attribute3": "Attribute 3" 
      }, 
      { 
       "attribute1": "Attribute 1", 
       "attribute2": "Attribute 2", 
       "attribute3": "Attribute 3" 
      }, 
     ] 
    } 
} 

是否有可能反序列化任一成相同的模型不知何故?也许那里有孩子(如ChildString & ChildObject)被相应地填充这取决于型2个不同的属性?

我目前使用Jil的反序列化,但我对其他人开放如果需要的话。

谢谢!

+0

请参阅http://michaelcummings.net/mathoms/using-a-custom-jsonconverter-to-fix-bad-json-results/ – jmoreno

回答

0

你可以使用一个通用的类型child并通过两种不同的类型取决于您的JSON:

class Parent<T> 
{ 
    public T child { get; set; } 
} 

class child 
{ 
    string attribute1 { get; set; } 
    string attribute2 { get; set; } 
    string attribute3 { get; set; } 
} 

var parentWithList = JsonConvert.DeserializeObject<Parent<List<string>>>(yourFirstJson); 

var parentWithSingleChild = JsonConvert.DeserializeObject<Parent<child>(yourSecondJson); 
0

一种解决方案可以尝试类似下面的

using System; 
using System.Collections.Generic; 
using System.IO; 
using Jil; 

namespace ConsoleApplication 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 

      var f=File.ReadAllText("requestAsString.json"); 
      var f1 = File.ReadAllText("requestAsObject.json"); 

      Root<List<string>> requestAsString = null; 
      try 
      { 
       requestAsString= JSON.Deserialize<Root<List<string>>>(f, Options.CamelCase); 
      } 
      catch (Exception) 
      {     
      } 
      Root<List<Child>> requestAsObject=null; 
      try 
      { 
       requestAsObject = JSON.Deserialize<Root<List<Child>>>(f1, Options.CamelCase); 
      } 
      catch (Exception) 
      {         
      } 





     } 
    } 

    class Root<T> 
    { 
     public Parent<T> Parent { get; set; } 
    } 
    class Parent<T> 
    { 
     public T Child { get; set; }   
    } 


    class Child 
    { 
     public string Attribute1 { get; set; } 
     public string Attribute2 { get; set; } 
     public string Attribute3 { get; set; } 
    } 


} 

但你应该确保您的要求是有效的(RFC 4627)

示例:

{ 
    "parent": { 
    "child": [ 
     "item 1", 
     "item 2", 
     "item 3" 
    ] 
    } 
} 
相关问题