How to add a parent to every child in a json array? - c#

I'm working on a Web Service in ASP.NET that has two methods, what I want to do is to return the data in JSON format, I'm usin JSON.NET library.
This is one of the methods:
[WebMethod]
public string GetReservas()
{
var json = "";
var data = from result in DCHotel.visHTLReservaciones select result;
json = JsonConvert.SerializeObject(data);
return json;
}
When I run the web service, this is the output in my browser:
[{"id":1,"name":"jose","age":22},{"id":2,"name":"john","age":21}]
And what I need is something like this:
["person":[{"id":1,"name":"jose","age":22}],"person":[{"id":2,"name":"john","age":21}]]
I need to add parents to every child in the array, I don't know how to do it, and I searched a lot and can't find the solution to this, hope you can help me.
Thanks.

It's very easy, change your linq query to this:
var data = from result in DCHotel.visHTLReservaciones select new { person = result };
Instead of taking just the result you encapsulate it on an anonymous class.
Cheers.

Related

Processing JSON response in Azure Function from query to Azure IOT Hub

I'm new to C# and having trouble processing queries into the desired format. If i run the code this way the response is:
["{\r\n \"Plant\": \"1195118\"\r\n}","{\r\n \"Plant\": \"1195157\"\r\n}"]
Which isn't the desired result. The actual desired output is a JSON of the following format:
{
"plant":["123235", "1195157"]
}
The code i'm using is below. I have tried several options but i'm struggling with the C# handling of JSON.
Any help would be appreciated. Thanks.
string queryString = "SELECT properties.reported.Plant_Number FROM devices WHERE properties.reported.Plant_Number != null";
IQuery query = registryManager.CreateQuery(queryString);
var json = (await query.GetNextAsJsonAsync());
return (ActionResult)new OkObjectResult(json);
The JSON you want is a single object, and the JSON you are getting is an array with one entry that is a string. In short: you need to parse the JSON.
var json = (await query.GetNextAsJsonAsync());
return (ActionResult)new OkObjectResult(json);
The first line returns an enumerable of strings, the second line returns it to the caller. So that's why the result you are getting is an array with strings.
If you want it to returns JSON instead, you will need to parse the string. To do that, you can use the JsonConvert class in the NewtonSoft.Json library (comes with your Function by default). You can learn about that here.
Edit after author's comment:
var jsonStrings = await query.GetNextAsJsonAsync();
var deviceProperties = jsonStrings.Select(JsonConvert.DeserializeObject<DeviceProperty>);
return (ActionResult)new OkObjectResult(deviceProperties);
public class DeviceProperty
{
public string Plant { get; set; }
}

pulling a python list out of a json object and converting it to something usable in C#

I have a python server that sends a list of strings as a json object to a C# client. On the client end I have this code to deserialize the object:
try
{
var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
var jsonObject = serializer.DeserializeObject(sr.ReadToEnd());
textBox4.Text = jsonObject.ToString();
}
catch (Exception e){
textBox2.Text = e.ToString();
}
What i'm getting as a result is: "System.Object[]"
Ideally I would like to put the contents of the list into an array.
can anyone point me in the right direction?
You are getting an array of generic objects, however I supose that you don't want this and you prefer getting a more usable result, so:
Create a class with the object's properties (for example: id, name, etc.). You can use this page in order to autogenerate the class.
Then deserialize the input into objects of the class that you have created in the first step, with the following code:
MyNewClass myNewClassList = serializer.Deserialize<MyNewClass>(sr.ReadToEnd());
I hope this can help you
Edit
This is a complete example created with the new information that you tell me in the comments:
var json = "[\"file0\",\"file1\",\"file2\",\"file3\",\"file4\",\"file5\"]";
var serializer = new JavaScriptSerializer();
var files = serializer.Deserialize<List<String>>(json);

convert dynamic object to C# object

I’m looking to take a dynamic object from a third party API & convert to my C# object with minimal code.
Sort of like what Dapper does with a SQL statement results to a C# object. Is there a library that would do this?
I can do it manually like below, but it seems like alot of code to write everytime I want to retrieve from this API.
public IEnumerable<Requirement> Get()
{
dynamic requirementsSelect;
requirementsSelect = _RequirementsRepository.GetRequirements();
IList<Requirement> Requirements = new List<Requirement>();
foreach (var req in requirementsSelect)
{
Requirement requirement = new Requirement();
requirement.Text = req.Text;
requirement.Number = req.Number;
Requirements.Add(requirement);
foreach (var node in req.Phrases)
{
Requirement reqNode = new Requirement();
reqNode.Text = node.Text;
reqNode.Number = node.Number;
requirement.Nodes.Add(reqNode);
}
return Requirements;
}
Thanks
I ended up returning the third party as JSON as follows. In my specific case the JSON wasn't showing the properties. I resolved by changing the dynamic object to IEnumerable and I was then able to specify which properties I wanted to retrieve using .Select.
IEnumerable<dynamic> requirements = _RequirementsRepository.GetRequirements();
return JsonConvert.SerializeObject(new
{
Requirement = requirements.Select(x => x.Text),
Number = requirements.Select(x => x.Number),
});
Thanks!

Get partial object list from JSON C#

I am calling a RESTful service in C# and the result is similar to this:
{
"blabla":1,
"bbb":false,
"blabla2":{
"aaa":25,
"bbb":25,
"ccc":0
},
"I_want_child_list_from_this":{
"total":15226,
"max_score":1.0,
"I_want_this":[
{
"A":"val1",
"B":"val2",
"C":"val3"
},
{
"A":"val1",
"B":"val2",
"C":"val3"
}
...
]
"more_blabla": "fff"
...
}
I want to get the "I_want_this" part as a list of object or JObject
Is there something like
(JObject)responseString["I_want_child_list_from_this"]["I_want_this"]
more generically:
(JObject)responseString["sub"]["sub_sub"]
I am using Newtonsoft.Json
Thanks!
First off, I would create a class that represents the JSON structure returned from the service call. (http://json2csharp.com/ great utility for auto-generating classes from JSON)
Second, if you are not using Newtonsoft.Json library, I would recommending grabbing that library.
Lastly, use Newtonsoft to deserialize the JSON from the service call into the class you created:
var json = Service.GetJson();
var yourDesiralizedJson = JsonConvert.DeserializeObject<YourJsonToCSharpClass>(json);
var listYouWant = yourDesiralizedJson.IWantChildList.IWantThis;
The below link is appears to be close to the solution as the requester using NewtonSoft.Json as his api to manipulate the object. Appreciate the solutions from other users as well.
look at e.g. here newtonsoft.com/json/help/html/SerializingJSONFragments.htm
The best solution (imo) is to define classes that describe your JSON schema then use DeserializeObject, as suggested by ertdiddy. As a shortcut, you can use DeserializeAnonymousType with incomplete definitions of your schema, taking advantage of JSON's leniency. In your case, this code is working for me:
var testDataFromQuestion = #"
{
""blabla"":1,
""bbb"":false,
""blabla2"":{
""aaa"":25,
""bbb"":25,
""ccc"":0
},
""I_want_child_list_from_this"":{
""total"":15226,
""max_score"":1.0,
""I_want_this"":[
{
""A"":""val1"",
""B"":""val2"",
""C"":""val3""
},
{
""A"":""val1"",
""B"":""val2"",
""C"":""val3""
}
],
""more_blabla"": ""fff""
}";
var anonymousDefinitionOfJson = new {
I_want_child_list_from_this = new {
I_want_this = new Dictionary<string, string>[] {}
}
};
var fullDeserializationOfTestData =
JsonConvert.DeserializeAnonymousType(testDataFromQuestion,
anonymousDefinitionOfJson);
var stuffYouWant = insterestingBits.I_want_child_list_from_this.I_want_this;
Console.WriteLine($"The first thing I want is {stuffYouWant[0]["A"]}");
This outputs the expected value "val1". I'm anonymously defining the minimal classes that get just the data you want, then I'm asking Newtonsoft to parse just enough to populate those classes.

converting list to json format - quick and easy way

Let's say I have an object MyObject that looks like this:
public class MyObject
{
int ObjectID {get;set;}
string ObjectString {get;set;}
}
I have a list of MyObject and I'm looking to convert it in a json string with a stringbuilder. I know how to create a JavascriptConverter and create a json string by passing a list and having the converter build the string but in this particular case I'm looking to avoid the overhead and go straight to a json string with a foreach loop on the list like this:
StringBuilder JsonString = new StringBuilder();
foreach(MyObject TheObject in ListOfMyObject)
{
}
I've tried to use this method by appending with commas and quotes but it hasn't worked out (yet).
Thanks for your suggestions.
I've done something like before using the JavaScript serialization class:
using System.Web.Script.Serialization;
And:
JavaScriptSerializer jss = new JavaScriptSerializer();
string output = jss.Serialize(ListOfMyObject);
Response.Write(output);
Response.Flush();
Response.End();
3 years of experience later, I've come back to this question and would suggest to write it like this:
string output = new JavaScriptSerializer().Serialize(ListOfMyObject);
One line of code.
For me, it worked to use Newtonsoft.Json:
using Newtonsoft.Json;
// ...
var output = JsonConvert.SerializeObject(ListOfMyObject);
I would avoid rolling your own and use either:
System.Web.Script.JavascriptSerializer
or
JSON.net
Both will do an excellent job :)
why reinvent the wheel? use microsoft's json serialize or a 3rd party library such as json.NET
I prefer using linq-to-json feature of JSON.NET framework. Here's how you can serialize a list of your objects to json.
List<MyObject> list = new List<MyObject>();
Func<MyObject, JObject> objToJson =
o => new JObject(
new JProperty("ObjectId", o.ObjectId),
new JProperty("ObjectString", o.ObjectString));
string result = new JObject(new JArray(list.Select(objToJson))).ToString();
You fully control what will be in the result json string and you clearly see it just looking at the code. Surely, you can get rid of Func<T1, T2> declaration and specify this code directly in the new JArray() invocation but with this code extracted to Func<> it looks much more clearer what is going on and how you actually transform your object to json. You can even store your Func<> outside this method in some sort of setup method (i.e. in constructor).
You could return the value using
return JsonConvert.SerializeObject(objName);
And send it to the front end
If you are using WebApi, HttpResponseMessage is a more elegant way to do it
public HttpResponseMessage Get()
{
return Request.CreateResponse(HttpStatusCode.OK, ListOfMyObject);
}

Categories

Resources