In my C# lambda I retrieve an item from DynamoDB. It is returned as a Dictionary<string, AttributeValue>. Is there a good way to serialize that to JSON?
The AttributeValue class exposes a bunch of properties to retrieve values of different types. If you do a simple serialization each one of those properties shows up in the JSON, most of them null, and makes a really messy object.
I want it to recognize a map and turn it into a JSON object, recognize a list and turn it into a JSON list. Basically, I want the object the Item represents.
You can use an alternate approach in C# to connect to DynamoDB using the DocumentModel. This DocumentModel has a ToJson() function.
Table table = Table.LoadTable(client, "yourtable");
Document document = table.GetItem(123);
string strJSON = document.ToJson();
Related
I have a scenario where I read the data from multiple json files and map them to certain Json format.
e.g. file1, file2, file 3
jsonoutput:
{
"parentfile1":"file1content",
"parentfile2":"file2content",
"parentfile3" : "file3content" and so on.
}
I am trying to map the input from the file reading directly to the valid json format to avoid reading all the files in one jsonObj, mapping it into one Object(class) and adding each parameter in the new object to create the jsonoutput.
I'd also like to handle shared mutable state while merging these json contents so I am using a lock(obj), the method that does this mapping is an async method.
I am using a JSchema to generate the schema of expected json format, :
check if the object in this schema contains the key(in the file), (not sure if this is possible??)
get it's parent name from the schema and add the parent name with the value(file content jsonobject) in the one JsonObject and
finally Deserialize the JSonObject in 2 to the expected file output.
Not sure if this is the best approach. Are there any other suggestion/ best practices to resolve this scenario?
I figured out one way to do this.
Generate the schema using JSchema
Get the properties of this schema -> Returns IDictionary with string as key-> property name and JSchema as value(child parameters/properties of the key)
Loop through the dictionary and get properties.value of the JSchema in 2
Loop through the List returned in 3-> List of keys
Add parent key as value and child key as key in the dictionary.
Now when adding the obj(file content) in the parent JObject, merge newJObject(parentkey, child object)
I'm working on a dynamic import proces from Json to object array.
Getting a little bit stuck by creating a List<> based on a string reference to the class object.
I'm importing json data from a REST server and using a business objects list to map the json data to predefined classes that can be configured. I'm using NewtonSoft.Json for the parsing of the data to classes.
string classname = "BusinessObjects.Contact";
Type classtype = Type.GetType(classname);
// ... filled jsonstring from api request
string json = "[]"; // json filled from rest request
JObject obj = JObject.Parse(json);
JArray array = (JArray)obj["contacts"];
// the issue part...
var records = array.ToObject<List<classtype>>();
The compiler states I'm using a variable as a type. Which makes sense, but can't find a way around it.
Any help would be appreciated!
Rather than deserializing your JArray, you could access it dynamically as shown in Querying JSON with dynamic. But if you would prefer to deserialize to a fixed list type, since you are writing non-generic reflection-based code, you can do:
var listType = typeof(List<>).MakeGenericType(classtype);
var records = array.ToObject(listType);
Notes:
Given an open generic type such as List<>, Type.MakeGenericType() creates a closed generic type by substituting the Type argument(s) for the type parameters of the open type.
JToken.ToObject() is a non-generic version of ToObject() that can deserialize to a specified Type.
Once you have created your records list you can cast it to the non-generic IList interface to access collections items.
Sample fiddle with prototype sample JSON and definition for BusinessObjects.Contact.
I am working on a project that communicates a lot of data with a server. This data is in a json format. We end up creating a lot of dummy objects to parse the json data. This leads to having a lot of classes that just contain class members. Is there a better way of doing things?
thanks
Assuming that you are using NewtonSoft's JSON parser or something similar, you have a couple of choices here. The usual use case here is to deserialize to a named type, thus:
var parsedMessage = JsonConvert.DeserializeObject<Message>(content.AsString());
If you have many types for each differnet JSON message type you wish to receive and wish to avoid to, you can do the following:
var parsedMessage = JsonConvert.DeserializeObject<dynamic>(content.AsString());
This will give you a dynamic object that you can inspect and should also work given other Json libraries. Alternatively, NetwtonSoft also provides the following method:
public static T DeserializeAnonymousType<T>(string value, T anonymousTypeObject);
This will allow you to deserialize to an anonymously typed object rather than a dynamic object.
I am writing a C# wrapper for a RESTful JSON API, and using Json.NET to deserialize the incoming json to strongly typed object. but a few properties in the incoming json are highly dynamic, it will be some json object with different number and type of properties. My current solution is, I mapped the dynamic json property to Dictionary<string, object> (Nested dictionary) in my C# class,and write Custom JsonConverter to convert dynamic json to Nested dictionary. My class look like this:
public class Item
{
[JsonProperty("item_id")]
public int ItemId { get; set; }
[JsonProperty("type")]
public string Type { get; set; }
//Property to map dynamic json object
[JsonProperty("data")]
public Dictionary<string, object> Data { get; set; }
}
It was successful.
The problem is, its very difficult to to access data from this nested dictionary for the end users, we can't even see what is the structure of data without debugging it in Visual studio. Now i am planning to use JObject or JArray instead of nested dictionary. So that we can see the structure of data by just calling ToString method (Will output the original json data as string) as well as this types have LINQ support so that users can access data from it easily.
Is this a good practice use this, considering JObject and JArray types both depend on a third party library (Anyway Json.NET is a dependency for my library because i am using it for json serialization) . Or there some other ways to do this ?
You should use ExpandoObjectConverter instead.
You need to type your IDictionary<string, object> as just dynamic and decorate the whole property with [JsonConverter(typeof(ExpandoObjectConverter))].
One interesting detail is ExpandoObject also implements IDictionary<string, object>, but when you type it with dynamic, you can access associated properties like regular ones! ;)
The serialization of the array returns the following JSON:
[{"Code":"AAAA","Description":"Description of AAAA"},{"Code":"BBBB","Description":"Description of BBBB"}]
My goal is to return the following JSON:
{"AAAA":{"Description":"Description of AAAA"},"BBBB":{"Description":"Description of BBBB"}}
You can achieve something simliar (not exactly the same you are expecting) if instead of serializing an array, build a temporary Dictionary and serialize it.
var dict = new Dictionary<String, YourClass>();
foreach (YourClass yourObj in listOfObjs)
{
dict[yourObj.Code] = yourObj;
}
// then serialize "dict"
You could add a rule to your JSON serializer to make it avoid serializing "code" property in YourClass, and you will end up with a JSON object exactly as you show in your example.
You'll need to either use a class that has the "AAAA" and "BBBB" properties, or you'll need to serialize a dictionary instead. As it is, you're serializing an array and getting an array.
The table on this blog post shows several search starting points.
.Net has built-in System.Web.Script.Serialization.JavaScriptSerializer, here, with examples
The .Net one doesn't specially serialize Dictionary the way you want, but some of the others do, I believe. However, I think there are reasons NOT to want a general serialization routine the way you've requested - though I can't list them certainly.