0

I am trying to deserialize a Jsonstring to c# listObject. The data is coming from javascript with:

params = "data=" + JSON.stringify(queryResult.$$rows);      
XHR.setRequestHeader("Content-type", "application/x-www-form-urlencoded");  
XHR.setRequestHeader("Content-length", params.length);      
XHR.setRequestHeader("Connection", "close");
XHR.send(params);

Then in asp.net try to deserialize the Jsonstring with:

public class HomeController : Controller
{
    [HttpPost]
    public ActionResult doWork(string data) 
    {
        var dump = JsonConvert.DeserializeObject<List<RootObject>>(data);
        return new EmptyResult();
    }   
}



public class RootObject
{
    public string data { get; set; }
    public string text { get; set; }
}

If i'm looking in the local variabel data. I found a valid jsong string:

[  
   [  
      {  
         "data":"Australia",
         "text":"Australia"
      }
   ],
   [  
      {  
         "data":"China",
         "text":"China"
      }
   ],
   [  
      {  
         "data":"Hong Kong",
         "text":"Hong Kong"
      }
   ],
   [  
      {  
         "data":"Indonesia",
         "text":"Indonesia"
      }
   ],
   [  
      {  
         "data":"Netherlands",
         "text":"Netherlands"
      }
   ]
]

When asp.net is trying to execute JsonConvert.DeserializeObject>(data); it wil return a error message:

JsonSerializationException was unhandled by user code an exception of type 'Newtonsoft.Json.JsonSerializationException' occred in newTonisoft.Json.ddl but was not handled in user code

Additional information: Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'maps.Controllers.RootObject' because the type requires a JSON object (e.g. {"name" : "value"}) to deserialize correctly.

How do i fix this? and is this the right javascript way?

user3432681
  • 564
  • 4
  • 10
  • 25
  • 1
    `List[]` is your json format – Sky Fang Jul 13 '15 at 14:39
  • Have you looked at other answers on StackOverflow? Like this one: http://stackoverflow.com/questions/17762032/cannot-deserialize-the-current-json-array-e-g-1-2-3-into-type – Rick S Jul 13 '15 at 14:40

1 Answers1

1
string jsonTxt = @"[  
[  
    {  
        ""data"":""Australia"",
        ""text"":""Australia""
    }
],
[  
    {  
        ""data"":""China"",
        ""text"":""China""
    }
],
[  
    {  
        ""data"":""Hong Kong"",
        ""text"":""Hong Kong""
    }
],
[  
    {  
        ""data"":""Indonesia"",
        ""text"":""Indonesia""
    }
],
[  
    {  
        ""data"":""Netherlands"",
        ""text"":""Netherlands""
    }
]
]";
var result = JsonConvert.DeserializeObject<List<RootObject>[]>(jsonTxt);

The result is your need

Sky Fang
  • 1,101
  • 6
  • 6