Reputation: 304
Below is a simplified snippet of my data.
{"doc":{"Identifier":"01967R0422-19990101","Year":[],"Embedding":"[0.001, -0.001, 0.002]"}}
I want to cast the embedding string to an array, with an output that looks as follows:
{"doc":{"Identifier":"01967R0422-19990101","Embedding":[0.001, -0.001, 0.002]}}
Some approaches that I have thought of are using Regex, or deserializing the object. However, attempts to deserialize the object has returned some errors
Attempt:
JsonConvert.DeserializeObject<Dictionary<string, string>>(json);
Error:
+ e {"Unexpected character encountered while parsing value: {. Path 'doc', line 1, position 8."} System.Exception {Newtonsoft.Json.JsonReaderException}
Could anyone please point me in the right direction? New to C# and regex, so the concepts are all pretty new to me. Thanks in advance!
Upvotes: 1
Views: 249
Reputation: 766
As i understand the question you want to use the json response in your code after you change how it is structured? I might be wrong correct me here. But if you really just need to change the json string and send it forward @Matthias L has the answer. But if you want to deserialize the JSON and use the object in your code.. please structure the Type/Object in a way the JSON string is deserializable to.
// Also here some Arrays are structured as [] and some are structured this way "[]"
var json = "{\"doc\":{\"Identifier\":\"01967R0422-19990101\",\"Year\":[],\"Embedding\":\"[0.001, -0.001, 0.002]\"}}";
json = json.Replace("\"[", "[");
json = json.Replace("]\"", "]");
using System.Text.Json;
using System.Text.Json.Serialization;
public class Rootobject
{
[JsonPropertyName("doc")]
public Doc Doc { get; set; }
}
public class Doc
{
[JsonPropertyName("Identifier")]
public string Identifier { get; set; }
[JsonPropertyName("Year")]
public object[] Year { get; set; }
[JsonPropertyName("Embedding")]
public object[] Embedding { get; set; }
}
// Also i use JsonSerializer, you could use the JsonConvert too.
var new_object = JsonSerializer.Deserialize<Rootobject>(json);
// You can use the new_object now in memory
// All further serializations from here wont have the "[]"
Upvotes: 0
Reputation: 13571
If you want an output that looks like:
{"doc":{"Identifier":"01967R0422-19990101","Embedding":[0.001, -0.001, 0.002]}}
You need a type that looks like that.
public class DS {
public string Identifier {get;set}
public List<decimal> Embedding {get;set}
}
Upvotes: 1
Reputation: 111
try sanitizing the json-string before deserealizing it:
string json = "{\"doc\":{ \"Identifier\":\"01967R0422-19990101\",\"Embedding\":\"[0.001, -0.001, 0.002]\"}}";
json = json.Replace("\"[", "[");
json = json.Replace("]\"", "]");
JsonConvert.DeserializeObject<Dictionary<string, string>>(json);
Upvotes: 2