3
votes

How to parse this json list at c# ? I have read this list at my service side.I using web api .

[
{ "Id":1,
  "Adjustment":{
    "CardNumber": "1234567895678",
    "TimeStamp": "2016-06-14 12:00:56",
    "Point": -13.09
    }
},
{ "Id":2,
  "Adjustment":{
    "CardNumber": "2345673245689",
    "TimeStamp": "2016-06-14 12:05:43",
    "Point": 2.3
    }
}
] 

I done this way but it is not working :How can I fixed my code? Do you have any suggestions ?I sent to request body with Fiddler.

public object InsertNewCustomer([FromBody] object value)
{
    var returns = new List<object>();

    if (value == null)
    {
        returns.Add(new { ReturnCode = "-1" });

        return Json(returns, JsonRequestBehavior.AllowGet).Data;
    }
    var jsonstr = @value.ToString();

    var jsonVal = JArray.Parse(jsonstr);



    Cariler newcustomer = new Cariler();

    using (TransactionScope scope = new TransactionScope())
    {

        foreach (JObject root in jsonVal)
        {
            foreach (KeyValuePair<String, JToken> app in root)
            {

                var card = (String)app.Value["CardNumber"];
                var time = (String)app.Value["TimeStamp"];
                var point = (byte)app.Value["Point"];

                newcustomer.CardNum = card;
                newcustomer.Time = time;
                newcustomer.Point = point;
                context.Cariler.Add(newcustomer);
                context.SaveChanges();
            }
        }


        scope.Complete();
        returns.Add(new { ReturnCode = "0" });

        return Json(returns, JsonRequestBehavior.AllowGet).Data;
    }
}

Giving this error :

{"Message":"An error has occurred.","ExceptionMessage":"Cannot access child value on Newtonsoft.Json.Linq.JValue.","ExceptionType":"System.InvalidOperationException","StackTrace":" at Newtonsoft.Json.Linq.JToken.get_Item(Object key)\r\n at TestWebApi.Controllers.ValuesController.InsertNewCustomer(Object value) in c:\Users\sezer.erdogan.PROMAKS\Desktop\LYLWebApi\LYLWebApi\Controllers\ValuesController.cs:line 64\r\n at lambda_method(Closure , Object , Object[] )\r\n at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.<>c__DisplayClass10.b__9(Object instance, Object[] methodParameters)\r\n at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.Execute(Object instance, Object[] arguments)\r\n at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ExecuteAsync(HttpControllerContext controllerContext, IDictionary2 arguments, CancellationToken cancellationToken)\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter1.GetResult()\r\n at System.Web.Http.Controllers.ApiControllerActionInvoker.d__0.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter1.GetResult()\r\n at System.Web.Http.Controllers.ActionFilterResult.<ExecuteAsync>d__2.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter1.GetResult()\r\n at System.Web.Http.Controllers.AuthenticationFilterResult.d__0.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()\r\n at System.Web.Http.Dispatcher.HttpControllerDispatcher.d__1.MoveNext()"}

3
Are we meant to guess how "it is not working"? What evidence do you have that it is not working? You should add that to your question. - spender
I added return error - Sezer Erdogan

3 Answers

6
votes

On json2csharp.com you can generate classes for your JSON, for your JSON they can look like:

public class Adjustment
{
    public string CardNumber { get; set; }
    public string TimeStamp { get; set; }
    public double Point { get; set; }
}

public class RootObject
{
    public int Id { get; set; }
    public Adjustment Adjustment { get; set; }
}

And then deserialise it:

List<RootObject> o = JsonConvert.DeserializeObject<List<RootObject>>(string json)
1
votes

Taking the json structure in your question, http://json2csharp.com/ gives us the following:

public class Adjustment
{
    public string CardNumber { get; set; }
    public string TimeStamp { get; set; }
    public double Point { get; set; }
}

public class RootObject
{
    public int Id { get; set; }
    public Adjustment Adjustment { get; set; }
}

Just accept them as an array in your controller action:

public class SomeController : ApiController
{
    public IHttpActionResult Post([FromBody] RootObject[] values)
    {
        // do stuff
        return Ok();
    }
}
0
votes

1) U have to send 1 class witch include list of models, instead list of classes

2) Create new class and copy your json

3) Edit > Paste Special > paste JSON as Class so now u have class

use this code to get data

RootObject answerFromServer = new RootObject();
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(RootObject));
answerFromServer = (RootObject)serializer.ReadObject(stream);

So now use your Root Class