POST request with JSON Body Serialization - c#

I have one specific issue, which I'm not able to handle.
I'm using HTTP Get API request and I'm getting JSON string, which I'm deserializing, this works perfectly. But then, I need to reuse just two pairs of this JSON file, but it needs to be pasted as JSON body for POST request. Let me show you the example:
Output of GET API Request:
{
"message":{
"value":[
{
"Reference":null,
"Key":"abc",
"IssueNumber":123
},
{
"Reference":null,
"Key":"def",
"IssueNumber":345
}
]
}
}
So now Im able to deserialize this JSON string (i.e.: jsonString("value)(0)("Key") and I will get "abc").
But now, I have no idea, how to serialize this deserialized object to use ReviewStatus and Key. This POST request JSON body looks like that:
{
"newStatus":"New"
"queueItems": [
{
"Key":"abc"
"IssueNumber":123
},
{
"Key":"def"
"IssueNumber":456
}
]
}
For loop works for me, but in that case, I will do API call for each item instead of doing just one POST API call. What would be the best solution in your opinion? I was trying to use Newtonsoft.Json.JsonConvert (SerializeObject Method), but it didn't work for me as I expected. I'm pretty sure, that there needs to be something much easier, but I need your help.
Thanks for any advice.
Frantisek

You can try to write two split species models, one for Receive JSON Modle, another for Response JSON Model.
Receive Modle
public class Value
{
public object Reference { get; set; }
public string Key { get; set; }
public int IssueNumber { get; set; }
}
public class Message
{
public List<Value> value { get; set; }
}
public class ReciveModel
{
public Message message { get; set; }
}
Response Model
public class QueueItem
{
public string Key { get; set; }
public int IssueNumber { get; set; }
}
public class ResponseModel
{
public string newStatus { get; set; }
public List<QueueItem> queueItems { get; set; }
}
Receive your JSON data and Deserialize to ReciveModel object, then let the data into another instance ResponseModel
final, you use JsonConvert.SerializeObject to serialize then instance to be JSON data.
var obj = JsonConvert.DeserializeObject<ReciveModel>(JsonData);
var res = new ResponseModel() {
newStatus = "New",
queueItems = obj.message.value.Select(x => new QueueItem() {
IssueNumber = x.IssueNumber,
Key = x.Key
}).ToList()
};
var jsonResult = JsonConvert.SerializeObject(res);
Result
{"newStatus":"New","queueItems":[{"Key":"abc","IssueNumber":123},{"Key":"def","IssueNumber":345}]}
c# online
Note
There are two way can create model easily.
You can use Web Essentials in Visual Studio, use Edit > Paste special > paste JSON as class, you can easier to know the relation between Json and model.
If you can't use Web Essentials you can instead of use http://json2csharp.com/ online JSON to Model class.
You can try to use those models to carry your JSON Format.

Related

JSON.NET: How to deserialize from specific json object to a class with a different name

This is driving me kinda nuts, because we don't have time to ask for the API team to change their response object name.
We have a json results that reads:
"seqRing": {
"admStatus": "disabled",
"status": null,
"lines": null
},
And I need that the json deserialization map it to this class:
public class SequentialRing
{
public string admStatus { get; set; }
public string status { get; set; }
public List<SeqLinesAttr> SeqLines { get; set; } = new List<SeqLinesAttr>();
}
If this were a case of a difference in the property name, I could simply use the JsonPropertyAttribute at the top of the property, but I need something similar for the class.
If there's something I could use? Please.
Thank you!
The JSON that you've shown has "seqRing" as a property of a larger JSON object. In order to deserialize that, you can create a wrapper class (or using an existing class) where you can specify the JSON property name for the class:
public class SequentialRingWrapper
{
[JsonProperty("seqRing")]
public SequentialRing SequentialRing { get; set; }
}

How to Deserialize JSON data? C#

Im getting a Json Data from an API and i have been trying to deserialize.
Json data:
{
   "items": [
      {
         "id": "1",
         "name": "samplename",
         "AddressList1": {
            "City": "Hyd",
            "State": "TN",
            "Country": "IN"
         },
         "Age": "10"
      },
      {
         "id": "2",
         "name": "samplename2",
         "AddressList1": {
            "City": "Hydd",
            "State": "TN",
            "Country": "IN"
         },
         "Age": "10"
      }
   ],
   "paging": {
      "cursors": {}
   }
}
Entities:
public class AddressList1
{
public string City { get; set; }
public string State { get; set; }
public string Country { get; set; }
}
public class Item
{
public string id { get; set; }
public string name { get; set; }
public AddressList1 addressList1 { get; set; }
public string Age { get; set; }
}
public class Cursors
{
}
public class Paging
{
public Cursors cursors { get; set; }
}
public class Users
{
public List<Item> items { get; set; }
public Paging paging { get; set; }
}
C# code:
JsonConvert.DeserializeObject<List<Users>>(content);
Error Message:
Cannot deserialize the current JSON object (e.g. {"name":"value"})
into type 'System.Collections.Generic.List`1[Entities.Users]'
because the type requires a JSON array (e.g. [1,2,3]) to deserialize
correctly.
where am i doing wrong?
The following is a JSON-object; in your case a User
{ ... }
The following is a JSON-array; in your case an array of User
[ { ... }, { ... } ]
Thus if you want to deserialize the JSON you got into an array of Users this is not possible because you have no array in JSON.
Therefore the right code to deserialize is:
JsonConvert.DeserializeObject<Users>(content);
Furthermore your mapping is erroneous because in JSON there is a property AddressList1 and in the class it is called addressList1
Given your JSON, you would need a POCO object that contains a items member and a paging member.
JsonConvert.DeserializeObject<Users>(content);
should work.
Your Json string is good formatted and the entities are according to Json2Csharp good too.
but your problem is with the instruction JsonConvert.DeserializeObject<List<Users>>(content);
all that json that you have is only ONE User, and you are trying to get a list of them, there is the issue,
you can try instead with:
JsonConvert.DeserializeObject<Users>(content);
Try Below Code
JsonConvert.DeserializeObject<Users>(content);
Your entities(models) look just fine. If you are using, or were to use ASP.NET Web API 2, and your client is using the http verb post for example, this setup would work as Web API takes care of the object deserialization:
public HttpStatusCode Post(Item item)
{
Debug.Write(item.toString());
return HttpStatusCode.OK;
}
If you insist in deserializing manually then use the JavaScriptSerializer library which allows you to do things like:
Item item = new JavaScriptSerializer().Deserialize<Item>(content);
Notice that .Deserialize<T>() takes a generic which in your case it Item.
Hope that helps.

Parse a Json String to create a new custom object c#

I am returning a json string to a WebMethod in WebForms and I want to take the json string and parse it into custom Order objects.
I have a class:
public class Order
{
public string Item { get; set; }
public string Color { get; set; }
public string Qty { get; set; }
public string Size { get; set; }
}
And a WebMethod:
[WebMethod]
public static string SendOrder(string json)
{
List<Order> orders = new List<Order>();
return json;
}
I am passing this string:
{
json: [
{
"Item":"Nike Polo #286772 - Women's Dri-FIT Micro Pique Short Sleeved Polo",
"Size":"XL",
"Color":"Light Blue",
"Quantity":"3"
},
{
"Item":"Port Authority Women's Jacket #L790 - Black",
"Size":"Medium",
"Color":"Black",
"Quantity":"3"
}
]
}
I want to loop through this string and creating new Orders.
What is the best way to do this?
That JSON is a little oddly formatted as it maps to the following classes (using http://json2csharp.com):
public class Json
{
public string Item { get; set; }
public string Size { get; set; }
public string Color { get; set; }
public string Quantity { get; set; }
}
public class RootObject
{
public List<Json> json { get; set; }
}
I'm not sure why you have a top-level variable named json, but whatever.
At this point just use JSON.NET to deserialize into the structure.
JsonConvert.DeserializeObject<RootObject>(yourJsonString);
If you want to rename the object from Json to Order you'll need to use an attribute for that. I don't recall the name off the top of my head but it should be easy to find in the JSON.NET documentation.
I recently completed a Windows Phone app that retrieved info from a Web API-based server as Json strings. I ended up using the JsonConvert class to convert my lists of objects from Json strings to my custom objects. Here's an example of one of my client-side methods that receives and converts the Json strings:
public async void GetGames()
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("base url");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = await client.GetAsync("specific url extention (like api/Order)");
if (response.IsSuccessStatusCode)
{
string s = await response.Content.ReadAsStringAsync();
var deserializedResponse = JsonConvert.DeserializeObject<List<Order>>(s);
//rest of code
}
}
}
Also, make sure that your web method is actually doing something. The example web method you posted creates creates a new list then just returns the parameter you passed in. Using Web API, you could return a list of all Order objects in your database via a method similar to the following:
public IQueryable<Order> GetOrders()
{
return db.Orders; //db is an instance of your DbContext class
}
I hope this is helpful. Let me know if you have any questions.

Parsing complex JSON text with Json.NET

I am writing a program to access Mediafire's web API and it's all going well, the only issue remaining is the response text in JSON format that I have difficulty parsing.
With API calls like creating a folder, I get a simple response which can be deserialized into a Dictionary<string,Dictionary<string,string>> and searched for values:
{"response":
{
"action":"folder\/create.php",
"name":"blargh",
"folder_key":"mmttuu769djo0",
"result":"Success",
"current_api_version":"2.14"
}
}
I would use it like this:
Dictionary<string,string> json = DeserializeJSON(text)["response"];
//DeserializeJSON is a method to shorten:
//JsonConvert.DeserializeObject<Dictionary<string,Dictionary<string,string>>(text)
I can then query for json["result"] and whatnot. With other API calls I get complex structures that I'm not sure how to handle. It's basically a bunch of key:value pairs, but some of the values are key:value pairs as well, which can't be put into a dictionary like I'm currently doing. I'm fairly new to C# so I'm not sure what to do here, is there some other data type like a Dictionary which doesn't have static types?
Here's the response:
{"response":
{
"action":"upload\/upload.php",
"doupload":
{
"result":"0",
"key":"89lh7760x4l"
},
"server":"live",
"result":"Success",
"current_api_version":"2.14"
}
}
My question would be: What is a good way to get this kind of data into a list that I can query for values?
What about creating a new class(s) to deal with the json? You can generate classes by using json2csharp using the example json.
public class Doupload
{
public string result { get; set; }
public string key { get; set; }
}
public class Response
{
public string action { get; set; }
public Doupload doupload { get; set; }
public string server { get; set; }
public string result { get; set; }
public string current_api_version { get; set; }
}
public class RootObject
{
public Response response { get; set; }
}
Then you can deserialise the json using:
JavaScriptSerializer serializer = new JavaScriptSerializer();
var something = serializer.Deserialize<RootObject>(jsonString);
I ended up finding out about the dynamic type - Deserializing the text into a Dictionary<string,dynamic> allows it to have multiple types where some can be dictionaries as well. I can query it as I would expect but I just need to be sure what values are returned with each API call, and I need to cast it to a string.
string upload_key = (string)json["response"]["doupload"]["key"] //89lh7760x4l

Parsing JSON data in C#

I have a JSON data as follows
{"id": "367501354973","from": {
"name": "Bret Taylor",
"id": "220439" }
which is returned by an object(result) of IDictionary[String, Object]
In my C# code:
I have made a class for storing the JSON value which is as follows
public class SContent
{
public string id { get; set; }
public string from_name { get; set; }
public string from_id { get; set; }
}
My main C# function which stores the parses the JSON data and stores the value inside the class properties is as follows:
List<object> data = (List<object>)result["data"];
foreach (IDictionary<string, object> content in data)
{
SContent s = new SContent();
s.id = (string)content["id"];
s.from_name = (string)content["from.name"];
s.from_id = (string)content["from.id"];
}
When i execute this code, i get an exception saying System cannot find the Key "from.name" and "from.id"
When i comment the two lines (s.from_name = (string)content["from.name"];s.from_id = (string)content["from.id"];) my code runs fine.
I think i am not able to refer the nested JSON data properly.
Can anyone just validate it and please tell me how to refer nested data in JSON in C#?
Thanks
I'm not sure how you are parsing the JSON string. Are you using a class in the Framework to do the deserialization?
You could use the JavaScriptSerializer Class defined in the System.Web.Script.Serialization Namespace (you may need to add a reference to System.Web.dll)
Using that class, you would write your code like this:
public class SContent
{
public string id { get; set; }
public SFrom from { get; set; }
}
public class SFrom
{
public string name { get; set; }
public string id { get; set; }
}
Then deserialization looks like this:
var json = new JavaScriptSerializer();
var result = json.Deserialize<SContent>(/*...json text or stream...*/);
See JavaScriptSerializer on MSDN. You might also want to check out this similar question.

Categories