Create a json request object in c# - c#

[{
"channel_id":299,
"requests":[{
"order_id":3975,
"action":"REQUEST_LABELS"
}]
}]
How to create the above request in c# the requests can be multiple.
I am new to c# i tried the below:
Dictionary<long, List<object>> requestObject = new Dictionary<long, List<object>>();
List<object> listrequestObjects = new List<object>();
Request requestOb = new Request();
requestOb.order_id = 2372;
requestOb.action = "REQUEST_LABELS";
listrequestObjects.Add(requestOb);
requestObject.Add(2352635, listrequestObjects);
string requesttest = JsonConvert.SerializeObject(requestObject);
But getting a weird request. Please help.

The structure should look like :
public class Request
{
public int order_id { get; set; }
public string action { get; set; }
}
public class RootObject
{
public int channel_id { get; set; }
public List<Request> requests { get; set; }
}

You need to declare the root object also:
[Serializable]
public class Root {
public int channel_id;
public Request[] requests;
}
Then assign the value and serialize it:
var root = new Root();
root.channel_id = 299;
root.requests = listrequestObjects.ToArray();
string requesttest = JsonConvert.SerializeObject(root);

You can use Newtonsoft.Json.
try this
private JArray GetResponse()
{
var main_array = new JArray();
var channel_id = new JObject();
channel_id.Add("channel_id",299);
var request = new JArray();
var order_id = new JObject();
order_id.Add("order_id",3975);
var action = new JObject();
action.Add("action","REQUEST_LABELS");
request.Add(order_id);
request.Add(action);
main_array.Add(channel_id);
main_array.Add(request);
return main_array;
}

Please try the JavaScriptSerializer class available in namespace
using System.Web.Script.Serialization
JavaScriptSerializer js = new JavaScriptSerializer();
string result = js.Serialize(requestObject);
The requestObject list is your custom class with all necessary properties.
Thanks

Related

Sending List in http request in C#

I'm trying to send List (of strings) as http request to a flask python backend but I cant figure how to parse the list into json format to send that
I tryed this:
var myObject = (dynamic)new JsonObject();
myObject.List = new List<string>();
// add items to your list
according to this: C# HTTP post , how to post with List<XX> parameter?
but It's says that List isn't recognized.
any help or other method to do this?
Use JsonSerializer in order to convert any object to a string
var list = new List<string>();
httpClient.PostAsync(
"",
new StringContent(
System.Text.Json.JsonSerializer.Serialize(list),
Encoding.UTF8,
"application/json"));
If you need to send an object with a List property:
var list = new List<string>();
httpClient.PostAsync(
"",
new StringContent(
System.Text.Json.JsonSerializer.Serialize(new {List = list}),
Encoding.UTF8,
"application/json"));
please prefer this Microsoft documentation.
https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json/how-to?pivots=dotnet-7-0
using System.Text.Json;
namespace SerializeToFile
{
public class WeatherForecast
{
public DateTimeOffset Date { get; set; }
public int TemperatureCelsius { get; set; }
public string? Summary { get; set; }
}
public class Program
{
public static void Main()
{
var weatherForecast = new WeatherForecast
{
Date = DateTime.Parse("2019-08-01"),
TemperatureCelsius = 25,
Summary = "Hot"
};
string fileName = "WeatherForecast.json";
string jsonString = JsonSerializer.Serialize(weatherForecast);
File.WriteAllText(fileName, jsonString);
Console.WriteLine(File.ReadAllText(fileName));
}
}
}
// output:
//{"Date":"2019-08-01T00:00:00-
07:00","TemperatureCelsius":25,"Summary":"Hot"}

JSON Not Deserializing

This is one of my first ventures into WCF/JSON. I created a WCF Web Service. This is one of my methods. It is how I serialize the datable to JSON.
public string GetPrayers()
{
DataTable myDt = new DataTable();
myDt = sprocToDT("LoadPrayers");
string JSONString = string.Empty;
JSONString = JsonConvert.SerializeObject(myDt, Formatting.None);
return JSONString;
}
This returns a nice JSON Dataset:
{"GetPrayersResult":"[{\"prayerid\":2,\"prayer\":\"Please pray for my
dog Rusty. He has cancer
:(\",\"prayerCategory\":\"General\",\"prayerDate\":\"2017-06-10T21:24:16.1\",\"handle\":\"GuruJee\",\"country\":\"USA\"},{\"prayerid\":1,\"prayer\":\"Help
Me I need a appendectomy
STAT\",\"prayerCategory\":\"Sports\",\"prayerDate\":\"2017-04-10T20:30:39.77\",\"handle\":\"GuruJee\",\"country\":\"USA\"}]"}
When I go to deserialize it I get all nulls. Here is the classes I created:
public class PrayUpPrayers
{
public string prayer { get; set; }
public string prayerid { get; set; }
public string prayerCategory { get; set; }
public string prayerCategoryID { get; set; }
public string prayerDate { get; set; }
public string handle { get; set; }
public string country { get; set; }
}
public class ThePrayer
{
public PrayUpPrayers prayers { get; set; }
}
}
This is how I am retrieving the JSON:
void getData()
{
var request = HttpWebRequest.Create(string.Format(#"URLGoesHere"));
request.ContentType = "application/json";
request.Method = "GET";
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
if (response.StatusCode != HttpStatusCode.OK)
Console.Out.WriteLine("Error fetching data. Server returned status code: {0}", response.StatusCode);
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
var content = reader.ReadToEnd();
string foo = content.ToString();
var testing = JsonConvert.DeserializeObject<prayupapp.ModelClasses.PrayUpPrayers>(foo,
new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore
});
Testing is always null? Is the issue that I am serializing it wrong, could it be the class structure, or is it related to how I am deserializing it. One important note: I checked my JSON on one of these JSONClassesFromC# sites and it only returns the GetPrayersResult as the only class item. Ignoring completely my entire structure.
You didn't provide the code for sprocToDT, but it should create ThePrayer object witch should contain list of PrayUpPrayers
public class ThePrayer
{
public List<PrayUpPrayers> prayers { get; set; }
}
And then you should deserialize ThePrayer object, not PrayUpPrayers.
For example
PrayUpPrayers prayUpPrayers1 = new PrayUpPrayers
{
prayer = "Please pray for my dog Rusty. He has cancer",
prayerid = "2",
prayerCategory = "General",
prayerDate = "2017-06-10T21:24:16.1",
handle = "GuruJee",
country = "USA"
};
PrayUpPrayers prayUpPrayers2 = new PrayUpPrayers
{
prayer = "Help Me I need a appendectomy STAT",
prayerid = "1",
prayerCategory = "Sports",
prayerDate = "2017-04-10T20:30:39.77",
handle = "GuruJee",
country = "USA"
};
ThePrayer thePrayer = new ThePrayer
{
prayers = new List<PrayUpPrayers>
{
prayUpPrayers1, prayUpPrayers2
}
};
myDt in your code should be the same as thePrayer instance in my code.
JSONString = JsonConvert.SerializeObject(myDt, Formatting.None);
will provide Json that looks like
"{\"prayers\":[{\"prayer\":\"Please pray for my dog Rusty. He has
cancer\",\"prayerid\":\"2\",\"prayerCategory\":\"General\",\"prayerCategoryID\":null,\"prayerDate\":\"2017-06-10T21:24:16.1\",\"handle\":\"GuruJee\",\"country\":\"USA\"},{\"prayer\":\"Help
Me I need a appendectomy
STAT\",\"prayerid\":\"1\",\"prayerCategory\":\"Sports\",\"prayerCategoryID\":null,\"prayerDate\":\"2017-04-10T20:30:39.77\",\"handle\":\"GuruJee\",\"country\":\"USA\"}]}"
And deserialize will look like
var testing = JsonConvert.DeserializeObject<prayupapp.ModelClasses.ThePrayer>(foo,
new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore
});
that's simple. you should deserilze the output twice. try this:
var output= DeserializeObject<string>(foo);
var testing = JsonConvert.DeserializeObject<prayupapp.ModelClasses.PrayUpPrayers>(output,
new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore
});

Reading first item in serialized JSON

I am trying to get name from first item in deserialized JSON object.
When I debugged code, I found that jsonObject is converted to dictionary.
How can I get first item value from jsonObject.
var myJson= [
{name:'abc',city:'dallas'},
{name:'def',city:'redmond'},
{name:'ghi',city:'bellevue'},
]
JavaScriptSerializer jss = new JavaScriptSerializer();
var jsonObject = jss.Deserialize<dynamic>(myJson);
NameInFirstItem = jsonObject[0].name;
Create a class to hold your resulting object:
public class MyJsonResult
{
public string name { set; get; }
public string result { set; get; }
}
static void Main(string[] args)
{
string myJson = "[{ name: 'abc',city: 'dallas'},{ name: 'def',city: 'redmond'},{ name: 'ghi',city: 'bellevue'}]";
JavaScriptSerializer jss = new JavaScriptSerializer();
List<MyJsonResult> jsonResultList = jss.Deserialize<List<MyJsonResult>>(myJson);
var NameInFirstItem = jsonResultList.FirstOrDefault().name;
}
Or if you insist on using dynamic:
static void Main(string[] args)
{
string myJson = "[{ name: 'abc',city: 'dallas'},{ name: 'def',city: 'redmond'},{ name: 'ghi',city: 'bellevue'}]";
JavaScriptSerializer jss = new JavaScriptSerializer();
var jsonResultList = jss.Deserialize<List<dynamic>>(myJson);
// get first value by key from the dictionary
var NameInFirstItem = jsonResultList.FirstOrDefault()["name"];
}
I prefer the first method. If you add a third property to your json, you might get confused with type of the generated object, which is probably a list of key-value pairs for each object in your list.
Try this:
var NameInFirstItem = jsonObject[0]["name"];
You can deserialize the json with
public class Details
{
public string name { get; set; }
public string city { get; set; }
}
var res = JsonConvert.DeserializeObject<Details[]>(json);
var name = res[0].name;

Converting list of objects to json array

I have a List of class objects that have email address and status data members. I am trying to convert these to a json, making sure to have the "operations" word on the array.
This is my class:
class MyClass
{
public string email {get; set; }
public string status { get; set; }
}
This is my current code (not building):
List<MyClass> data = new List<MyClass>();
data = MagicallyGetData();
string json = new {
operations = new {
JsonConvert.SerializeObject(data.Select(s => new {
email_address = s.email,
status = s.status
}))
}
};
This is the JSON I am trying to get:
{
"operations": [
{
"email_address": "email1#email.com",
"status": "good2go"
},
{
"email_address": "email2#email.com",
"status": "good2go"
},...
]
}
EDIT1
I should mention that the data I am getting for this comes from a DB. I am de-serializing a JSON from the DB and using the data in several different ways, so I cannot change the member names of my class.
I believe this will give you what you want. You will have to change your class property names if possible.
Given this class
class MyClass
{
public string email_address { get; set; }
public string status { get; set; }
}
You can add the objects to a list
List<MyClass> data = new List<MyClass>()
{
new MyClass(){email_address = "e1#it.io", status = "s1"}
, new MyClass(){ email_address = "e2#it.io", status = "s1"}
};
Using an anonymous-type you can assign data to the property operations
var json = JsonConvert.SerializeObject(new
{
operations = data
});
class MyClass
{
public string email_address { get; set; }
public string status { get; set; }
}
List<MyClass> data = new List<MyClass>() { new MyClass() { email_address = "email1#email.com", status = "good2go" }, new MyClass() { email_address = "email2#email.com", status = "good2go" } };
//Serialize
var json = JsonConvert.SerializeObject(data);
//Deserialize
var jsonToList = JsonConvert.DeserializeObject<List<MyClass>>(json);
You can try with something like this:
using System.Web.Script.Serialization;
var jsonSerialiser = new JavaScriptSerializer();
var json = jsonSerialiser.Serialize(data);
Here is the simple code
JArray.FromObject(objList);

Why is my json deserialization failing?

I have the following two objects (which I do not control and can not change):
[Serializable]
[DataContract]
public class AddressContactType : BaseModel
{
public AddressContactType();
[DataMember]
public string AddressContactTypeName { get; set; }
}
[Serializable]
[DataContract]
public abstract class BaseModel
{
protected BaseModel();
[DataMember]
public int Id { get; set; }
[DataMember]
public string NativePMSID { get; set; }
[DataMember]
public string PMCID { get; set; }
}
I am using RestClient to make a GET call to retrieve this data in JSON. The request succeeds. The returned JSON is:
[{"Id":0,"NativePMSID":"1","PMCID":"1020","AddressContactTypeName":"Home"},{"Id":0,"NativePMSID":"2","PMCID":"1020","AddressContactTypeName":"Apartment"},{"Id":0,"NativePMSID":"3","PMCID":"1020","AddressContactTypeName":"Vacation"},{"Id":0,"NativePMSID":"3","PMCID":"1020","AddressContactTypeName":"Other"}]
From that point I attempt to deserialize the data in three different ways.
My code:
var request = new RestRequest("AddressContactType", Method.GET);
request.AddHeader("Accept", "application/json");
request.AddParameter("PMCID", "1020");
#region JSON Deserialization
// ---- Attempt #1
var response = client.Execute<AddressContactType>(request);
// ---- Attempt #2
var myResults = response.Content;
var ms = new MemoryStream(Encoding.UTF8.GetBytes(myResults));
var ser = new DataContractJsonSerializer(typeof(AddressContactType));
var result = (AddressContactType)ser.ReadObject(ms);
// ---- Attempt #3
var jsonSettings = new JsonSerializerSettings()
{
Formatting = Formatting.Indented,
DateFormatHandling = DateFormatHandling.MicrosoftDateFormat,
DateTimeZoneHandling = DateTimeZoneHandling.Utc,
PreserveReferencesHandling = PreserveReferencesHandling.Objects
};
var result2 = new AddressContactType();
result2 = JsonConvert.DeserializeObject<AddressContactType>(new StreamReader(ms).ReadToEnd(), jsonSettings);
#endregion
Under attempt 1, the RestClient attempt returns the error: "Unable to cast object of type 'RestSharp.JsonArray' to type 'System.Collections.Generic.IDictionary`2[System.String,System.Object]'."
Under attempt 2, the object result is shown with the correct properties (Id, NativePMSID, PMCID and AddressContactTypeName) but they are all null and only one instance of each is shown.
Attempt 3 just returns a null value for result2.
Any suggestions?
Thanks.
It appears the solution to my problem is:
List<AddressContactType> myResults2;
using (Stream ms2 = new MemoryStream(Encoding.UTF8.GetBytes(myResults)))
{
myResults2 = JsonConvert.DeserializeObject<List<AddressContactType>>(new StreamReader(ms2).ReadToEnd());
}
I was close with one of the previous steps, but this gave me a complete list.

Categories