RGroppa
RGroppa

Reputation: 325

How to use Newtonsoft to deserialize a json string to an anonymous type?

I have

var deserialized = JsonConvert.DeserializeObject("{'fielda':'1'}", typeof(object));
var updateDocument2 = new { fielda= "1" };

var s = deserialized.GetType();
var s2 = updateDocument2.GetType();

I want deserialized and updateDocument2 to be identical in type and contents so I can do:

var updateRequest = new UpdateRequest<object, object>(indexName, type, id)
  {
    Doc = deserialized 
  };       
var result = await client.UpdateAsync<object, object>(updateRequest);

The client is elasticsearch. I know that Doc = updateDocument2 works fine, but Doc = deserialized fails because the deserializer inside client.UpdateAsync gets confused.

Essentially I want to turn a string into an anonymous object so that I can update elasticsearch with it.

Thoughts?

Sample code for easy reproduction:

var deserialized = JsonConvert.DeserializeObject("{'fielda':'1'}", typeof(object));
var updateDocument2 = new { fielda = "1" };

var s = deserialized.GetType();
var s2 = updateDocument2.GetType();
Console.WriteLine($"Deserialized:\n {s}\n {deserialized.ToString()}");
            Console.WriteLine();
            Console.WriteLine($"Expected:\n {s2} \n {updateDocument2.ToString()}");
            Console.Read();

Output:

Deserialized:
 Newtonsoft.Json.Linq.JObject
 {
  "fielda": "1"
}

Expected:
 <>f__AnonymousType0`1[System.String]
 { fielda = 1 }

I'm prepared to convert the JObject to AnonymousType if that's possible, but I'm not sure that it is.

Upvotes: 0

Views: 638

Answers (1)

LadderLogic
LadderLogic

Reputation: 1140

Newtonsoft supports deserializing anonymous types out of the box. You just need to declare your type before you call the API. Something like this:

var deserializedDoc = new { fielda = string.Empty };
deserializedDoc = Newtonsoft.Json.JsonConvert.DeserializeAnonymousType(jsonString, deserializedDoc);

Newtonsoft Reference

Upvotes: 4

Related Questions