Format string for JSON

Asked

Viewed 749 times

2

I have the following code:

 public static string SendSMS(List<string> numbers, string usuario, string message)
        {

            int count = 0;
            string keerpersNumbers = "";
            string urlSMS = "https://minhaurl";
            string authHeader = "Basic bWFshkjhkj=";
            string contentTypeHeader = "application/json";

            if (numbers != null && numbers.Count > 0)
            {  //separar os numero para o json
                foreach (string num in numbers)
                {
                    //keerpersNumbers = num;
                    if (count > 0)
                    {
                        keerpersNumbers = keerpersNumbers + "," + num;
                    }
                    else
                    {
                        keerpersNumbers = num;
                    }
                    count++;
                }

                if (usuario == null && usuario.Equals(""))
                {
                    usuario = "app";
                }

            }

            var httpWebRequest = (HttpWebRequest)WebRequest.Create(urlSMS);
            httpWebRequest.ContentType = contentTypeHeader;
            httpWebRequest.Headers.Add("Authorization", authHeader);
            httpWebRequest.Method = "POST";
            httpWebRequest.Accept = contentTypeHeader;

            using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
            {
                string json = "{\"from\":\"InfoSMS\", \"to\":\"[5531989872881]\",\"text\":\"Test SMS.\"}";
                string contents = JsonConvert.SerializeObject(json);
                streamWriter.Write(json);
                streamWriter.Flush();
                streamWriter.Close();
            }

            var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
            using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
            {
                var result = streamReader.ReadToEnd();
            }

            return httpResponse.StatusCode.ToString();

        }
    }

Which works, but as you can see, is static. I would like this string json used the method variables, but, I try to format and always get error 400 from the server.

How to do this? Thank you!

EDIT:

JSON

{  
   "from":"WineShop",
   "to":[  
      "5531984882881",
      "5531984882881"
   ],
   "text":"Wine shop grand opening at Monday 8pm. Don't forget glasses."
}
  • you are sure that the number array should be an integer represented in a string? "[5531989872881]\"

  • I send a string, as you can see in the message parameters. JSON I will add in the question

  • So the displayed Json is different from what is stated in the code above the question

  • that’s the question, how to format json?

3 answers

1


Following the format presented in the first part of the question where the property to reflects the following structure "to":"[123456,12354]"... You can simply interpolate your string.

string json = $"{{\"from\":\"{usuario}\", \"to\":\"[{string.Join(',', numbers)}]\",\"text\":\"{message}\"}}";

Upshot

{"from":"Teste", "to":"[123456,123456,123456c]","text":"teste"}

Now in the second template presented later, you just create a POCO to reflect the desired structure and thus use the JsonConvert for the serialization and deserialization.

class JsonSMSRequest
{
    public string from { get; set; }
    public List<string> to { get; set; }
    public string text{ get; set; }
}

//...

var jsonObject = new JsonSMSRequest{ from = usuario, to = numbers, text= message };
var jsonString = JsonConvert.SerializeObject(jsonObject);

Upshot

{"from":"Teste","to":["123456","123456","123456c"],"text":"teste"}
  • This was really the problem he presented next, he read an entire string and the SMS didn’t arrive. I’ll test and return if it works, thank you very much!

  • worked right! thank you very much. I can not raise the reply

0

Hello i am also working with json created a file . json and added to my script in this way:

$.getJSON("dados.json", function(json) { 

 //aqui programas o que queres com o ficheiro json
 
 });

What’s between "" is the name of my file

and you can organize your file this way:

[
  {  
   "from":"WineShop",
   "to":5531984882881,
        5531984882881
   "text":"Wine shop grand opening at Monday 8pm. Don't forget glasses."
  }
]

Note: In non target numbers "".

0

Create an object to contain json data:

string numTel = "998877776";
string textoMSG = "teste teste";
object objMSG = new { from = "InfoSMS", to = numTel, text = textoMSG };

string json = JsonConvert.SerializeObject(objMSG);

the object objMSG can still be a class representing the MSG to be sent, with the from,to and text parameters.

  • Can make a foreach with the existing list of numbers numbers and in each loop of the for fulfills the classes and parameters for sending.

  • I already have this loop and it performs, should I insert the brackets in the number string? to indicate to json that it is a list?

  • only numbers are lists.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.