0

I want to post data to the database where I am fetching the data in a JSON format.

Here is the following JSON string:

"[{"cph_id":"67/123/7894","phone_no":"0000623019"},
{"cph_id":"69/213/1234","phone_no":"0000623019"}]"

I have also created the following classes:

public class RootObject
{
    public List<dlregistrationdata> data { get; set; }
}  

public class dlregistrationdata
{
    public string cph_id[] { get; set; }
    public string phone_no[] { get; set; }
} 

I try to deserialize using the following command:

 try
 {
   var obj = JsonConvert.DeserializeObject<List<dlregistrationdata>>(result);
   var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://172.61.25.30/CPRestApi/api/user/register");
   httpWebRequest.ContentType = "application/json";
   httpWebRequest.Method = "POST";
   if (email != null)
   {
      using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
       {
         dynamic arr = new JObject();
         for (int i = 0; i < obj.Count; i++)
         {
            arr.cph_id = obj[i].cph_id;
            arr.user_name = email;
            arr.user_phone_number = obj[i].phone_no;
            arr.user_password = password;
            arr.status = 1;
            arr.name = name;
         }
         streamWriter.Write(arr);
     }
 }

     var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
     if (httpResponse.StatusCode == System.Net.HttpStatusCode.Created)
     {
         using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
         {
             var result1 = streamReader.ReadToEnd();
         }
             return RedirectToLocal("Index");
     }
 }
 catch (Exception ex)
 {
    Console.WriteLine(ex.Message);
    ViewBag.ErrorMessage = "User Already Registered";
    ModelState.AddModelError("", "User Already Registered");
    return View(model);
 }

But I am getting the error: "converting value "67/123/7894" to type 'System.String[]'. Path '[0].cph_id', line 1, position 24"

Any help will be highly appreciated.

Thank You!

5
  • you definded cph_id as string so it is parsed as string Commented Aug 4, 2021 at 8:34
  • When I am changing the model to public string[] cph_id { get; set; } public string[] phone_no { get; set; }. I am getting the error "converting value "67/123/7894" to type 'System.String[]'. Path '[0].cph_id', line 1, position 24." Commented Aug 4, 2021 at 8:40
  • 3
    Simplify your problem, create a simple code to convert that part first. Once that is solved then apply that solution to this code. Commented Aug 4, 2021 at 8:43
  • 67/123/7894 is not an array a json array would look like ["67", "123", "7894"] so it can not be parsed to an array Commented Aug 4, 2021 at 8:55
  • 2
    Doesn't work like that; your JSON is an array-of-objects. Your code is an object-of-arrays. These two things are very different. Paste your JSON into QuickType.io and follow the instructions in the comments inside the c# it generates. Use JsonProperty attributes to specify the names in the Json rather than violating c# naming conventions to match your c# to the json Commented Aug 4, 2021 at 8:55

2 Answers 2

1

Changes made in model class:

public class dlregistrationdata
{
    public string cph_id { get; set; }
    public string phone_no { get; set; }
}

public class RequestRegistrationAPI { 
    public string user_name { get; set; }
    public string user_password { get; set; }
    public string user_phone_number { get; set; }
    public string name { get; set; }
    public int status { get; set; }
    public string[] cph_id { get; set; }
}

Changes made in code:

  using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
  {
      List<string> cphid = new List<string>();
      string phone_no = "";
      foreach (dlregistrationdata data in obj)
      {
          cphid.Add(data.cph_id);
          phone_no = data.phone_no;
      }

     RequestRegistrationAPI request = new RequestRegistrationAPI();
     request.user_name = email;                                
     request.user_password = password;
     request.user_phone_number = phone_no;
     request.name = name;
     request.cph_id = cphid.ToArray();
     request.status = 1;
                            
     streamWriter.Write(JsonConvert.SerializeObject(request));
 }

This works perfectly for me.

Sign up to request clarification or add additional context in comments.

Comments

0

change classes to :

public class dlregistrationdata
{
    public string cph_id { get; set; }
    public string phone_no { get; set; }
} 

now change code to :

var obj = JsonConvert.DeserializeObject<List<dlregistrationdata>>(result);
var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://172.61.25.30/CPRestApi/api/user/register");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
if (email != null)
{
    using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
    {
        dynamic arr = new JObject();
        for (int i = 0; i < obj.Count; i++)
        {
            arr.cph_id = obj[i].cph_id;
            arr.user_name = email;
            arr.user_phone_number = obj[i].phone_no;
            arr.user_password = password;
            arr.status = 1;
            arr.name = name;
        }
        streamWriter.Write(arr);
   }
}

3 Comments

But after run the project getting the error : Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'CP_Web.Models.RootObject' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.
I edited the code. It works now. I took a test.
Because you do not have a RootObject in the Json string, you must deserialize the string with a list of dlregistrationdata.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.