I'm reading my json file from and trying to replace the property values. JSON file is below.
{
"fields": {
"summary": "summaryValue",
"project": {
"key": "projectValue"
},
"priority": {
"name": "priorityValue"
},
"Requestor": {
"name": "RequestorValue"
},
"issue": {
"name": "issueValue"
},
"labels": "LabelValue",
"customfield_xyz": "customfield_xyzValue"
}
}
How can I replace the value for each item inside the fields property ?
for ex:
{"fields": {
"summary": "NewsummaryValue",
"project": {
"key": "NewprojectValue"
},
"priority": {
"name": "NewpriorityValue"
}
}
}
Below is the code to parse my json file,
StreamReader r = new StreamReader(filepath);
var jsondata = r.ReadToEnd();
var jobj = JObject.Parse(jsondata);
foreach (var item in jobj.Properties())
{
\\replace code
}
I do not know exactly what you want. But I changed the json information in the code snippet as you wanted.
dynamic dataCollection = JsonConvert.DeserializeObject<dynamic>(jsonData);
string summary = dataCollection["fields"]["summary"];
string project = dataCollection["fields"]["project"]["key"];
string priority = dataCollection["fields"]["priority"]["name"];
dynamic json = new JObject();
json.summary = summary;
json.project = project;
json.priority = priority;
dynamic jsonRoot = new JObject();
jsonRoot.fields = json;
Console.WriteLine(jsonRoot.ToString());
output:
Im facing a litle problem in Deserializing BsonDocuments type, I couldn't find the reason, but I have some clues, maybe, it's about {0 fields}, because the error tel me about the column I have {0 fields}. I also realised that its a {} (empty array).
MY MONGO QUERY ON ROBO 3T AND THE RESULT
MY C# MONGO QUERY
var connString = "mongodb+srv";
var client = new MongoClient(connString);
var database = client.GetDatabase("Base");
var collection = database.GetCollection<BsonDocument>("collection");
var match1 = new BsonDocument("$match", new BsonDocument("PartnerId", "2021"));
var match2 = new BsonDocument("$match", new BsonDocument("CD_CLIENTE", codCond));
var project = new BsonDocument { { "$project", new BsonDocument { { "_id", 0 }, { "CD_CLIENTE", 1 }, { "CD_ACESSO", 1 },
{ "ID_ACESSO", 1 },{ "NOME", 1 },{ "NU_TELEFONE", 1 }, { "EMAIL", 1 }, { "NU_KIPER_RF", 1 }, { "NU_KIPER_TAG", 1 },
{ "FG_KIPER_MOBILE", 1 },{ "KEY_HASH", 1 },}}}; MY MONGO AND RESULT
var sort = new BsonDocument("$sort", new BsonDocument("NOME", 1));
var pipeline = new[] { match1, match2, project, sort };
var result = collection.Aggregate<BsonDocument>(pipeline).ToList();
var lista = JsonConvert.DeserializeObject<List<UsuariosAcessos>>(result.ToJson());
The error is here:
var lista = JsonConvert.DeserializeObject<List<UsuariosAcessos>>(result.ToJson());
Exatly when I try to Deserialise an that "empty array" to Model int?. I found a work around, because I just need to know if, we have or dont not something in NU_KIPER_TAG and NU_KIPER_RF, so, I did this new Mongo query.
NEW MONGO QUERY USING $COND
db.dbACESSO.aggregate([
{
$match: { PartnerId: "2021", CD_CLIENTE: 4003}
},
{
$project: {_id:0, CD_CLIENTE:1, CD_ACESSO:1, ID_ACESSO:1, NOME:1, NU_TELEFONE:1,EMAIL:1, FG_KIPER_MOBILE:1,
TAG:{$cond: [{ $eq: [ "$NU_KIPER_TAG", {}]}, 0, 1 ]}, CONTROLE:{$cond: [{ $eq: [ "$NU_KIPER_RF", {}]}, 0, 1 ]},
APPATIVO:{$cond: [{ $eq: [ "$KEY_HASH", {}]}, "", "$KEY_HASH" ]}}
}
])
I couldnt translate it to C#, I tried hard, but i'm not familiarized with the sintaxe. I also googled for a sample with no success.
I think its something like:
var project = new BsonDocument {
{
"$project", new BsonDocument { { "_id", 0 }, { "CD_CLIENTE", 1 }, { "CD_ACESSO", 1 },{ "ID_ACESSO", 1 },{ "NOME", 1 }
,{ "NU_TELEFONE", 1 }, { "EMAIL", 1 }, { "NU_KIPER_RF", 1 }, { "NU_KIPER_TAG", 1 },{ "FG_KIPER_MOBILE", 1 },{ "KEY_HASH", 1 },
{"TAG", new BsonDocument{{"$cond", new BsonDocument {{ "$eq", "$NU_KIPER_TAG", "{}"}}, 0, 1 ]}, } }
}
}
};
Try this way, it will work!
var project = new BsonDocument
{
{
"$project", new BsonDocument
{
{ "_id", 0},
{ "CD_CLIENTE", 1},
{ "CD_ACESSO", 1 },
{ "NOME", 1},
{ "EMAIL", 1 },
{ "FG_KIPER_MOBILE", 1 },
{ "GRUPO", "$GRUPO.NM_DESCRICAO" },
{ "UNIDADE", "$UNIDADE.NM_DESCRICAO" },
{ "NU_TELEFONE", new BsonDocument{{ "$cond", new BsonArray{new BsonDocument{{"$eq", new BsonArray{ "$NU_TELEFONE", new BsonDocument { } } }}, "","$NU_TELEFONE" } }}},
{ "TAG", new BsonDocument{{ "$cond", new BsonArray{new BsonDocument{{"$eq", new BsonArray{ "$NU_KIPER_TAG", new BsonDocument { } } }}, 0,1 } }}},
{ "CONTROLE", new BsonDocument{{ "$cond", new BsonArray{new BsonDocument{{"$eq", new BsonArray{ "$NU_KIPER_RF", new BsonDocument { } } }}, 0,1 } }}},
{ "APPATIVO", new BsonDocument{{ "$cond", new BsonArray{new BsonDocument{{"$eq", new BsonArray{ "$KEY_HASH", new BsonDocument { } } }}, "", "$KEY_HASH" } }}},
}
}
};
The empty array will be represented for: new BsonDocument { }
{ "NU_TELEFONE", new BsonDocument{{ "$cond", new BsonArray{new BsonDocument{{"$eq", new BsonArray{ "$NU_TELEFONE", new BsonDocument { } } }}, "","$NU_TELEFONE" } }}},
What about using the fluent C# like this:
var connString = "mongodb+srv";
var client = new MongoClient(connString);
var database = client.GetDatabase("Base");
var collection = database.GetCollection<UsuariosAcessos>("collection"); //Here you put you Model
var filter = Builders<UsuariosAcessos>.Filter.Eq(x => x.PartnerId, cliente)
& Builders<UsuariosAcessos>.Filter.Eq(x => x.CD_CLIENTE, codCond);
var lista = collection.Aggregate().Match(filter).Project(x => new UsuariosAcessos
{
CD_CLIENTE = x.CD_CLIENTE,
ID_ACESSO = x.ID_ACESSO,
CD_ACESSO = x.CD_ACESSO,
NOME = x.NOME,
NU_TELEFONE = x.NU_TELEFONE,
EMAIL = x.EMAIL,
NU_KIPER_RF = x.NU_KIPER_RF,
NU_KIPER_TAG = x.NU_KIPER_TAG,
FG_KIPER_MOBILE = x.FG_KIPER_MOBILE,
KEY_HASH = x.KEY_HASH
}).ToList();
About your problem at Deserialization time, I think it's not possible to translate {} (empty array) to int or int?, it's appear to be the reason your deserialization is not working, try to change your model.
FROM:
public int? NU_KIPER_TAG { get; set; }
public int? NU_KIPER_RF { get; set; }
TO:
public object NU_KIPER_TAG { get; set; }
public object NU_KIPER_RF { get; set; }
Its not you are looking for, but, maybe your Deserialization are going to Work. After that, you can convert the data. Hope this helps.
In my project client send me this JSON string.
{
"onlineRequest": {
"CustomerCode": "AB432A",
"MobileNumber": "75484568",
"ProductNo": "100",
"JsonFile": {
"evaluation": {
"number": [
{
"#para-id": "5656",
"#new-code": "",
"#text": "Hello America"
},
{
"#para-id": "3302",
"#new-code": "100",
"#text": "Hello Japan"
}
]
}
}
}
}
This JSON contains inner JSON called JsonFile. Now I need to set the values to this JSON file as follows.
if #para-id = 5656, then #new-code = "0000"
if #para-id = 3302, then #new-code = "1111"
Expected Output:
{
"onlineRequest": {
"CustomerCode": "AB432A",
"MobileNumber": "75484568",
"ProductNo": "100",
"JsonFile": {
"evaluation": {
"number": [
{
"#para-id": "5656",
"#new-code": "0000",
"#text": "Hello America"
},
{
"#para-id": "3302",
"#new-code": "1111",
"#text": "Hello Japan"
}
]
}
}
}
}
How can I do this?
Can be easily done with Newtonsoft.Json:
var source = #"{
""onlineRequest"": {
""CustomerCode"": ""AB432A"",
""MobileNumber"": ""75484568"",
""ProductNo"": ""100"",
""JsonFile"": {
""evaluation"": {
""number"": [
{
""#para-id"": ""5656"",
""#new-code"": """",
""#text"": ""Hello America""
},
{
""#para-id"": ""3302"",
""#new-code"": ""100"",
""#text"": ""Hello Japan""
}
]
}
}
}
}";
var json = JToken.Parse(source);
var dict = new Dictionary<string, string>
{
["5656"] = "0000",
["3302"] = "1000",
};
foreach (var number in json.SelectToken("onlineRequest.JsonFile.evaluation.number").ToArray())
{
var id = (string)number["#para-id"];
if (id != null && dict.TryGetValue(id, out var code))
{
number["#new-code"] = code;
}
}
I got a json result as shown in image 1 but I need an output shown in image 2.
I took the following classes
public class NameDTO
{
public string Name;
}
public class ValDTO
{
public string Val;
}
I got the list to the above classes as shown in figure 3 and 4 and combining them and converting to json.
var combined1 = _nameDetials1.Zip(_valDetials1, (name1, val1) => new { name1.Name, val1.Val }) .ToDictionary(k => k.Name, k => k.Val);
var jsonSerialiser1 = new JavaScriptSerializer();
var json1 = jsonSerialiser1.Serialize(combined1);
How can I do the grouping so that I can get he correct output as shown in image2
Thanks.
If it is possible you can use Json.NET.
Here an example to solve your problem.
const string JSON = #"{
""message-Code-1"": ""000"",
""msg-Number-Pos1-1"": ""0000"",
""msg-Number-Pos2-1"": ""1"",
""msg-Number-Pos3-1"": ""1"",
""message-Code-2"": ""1"",
""msg-Number-Pos1-2"": ""0001"",
""msg-Number-Pos2-2"": ""2"",
""msg-Number-Pos3-2"": ""1"",
""message-Code-3"": ""0002"",
""msg-Number-Pos1-3"": ""3"",
""msg-Number-Pos2-3"": ""1"",
""msg-Number-Pos3-3"": ""1"",
""message-Code-4"": ""0003"",
""msg-Number-Pos1-4"": ""3"",
""msg-Number-Pos2-4"": ""1"",
""msg-Number-Pos3-4"": ""1""
}";
JObject loMessages = JObject.Parse(JSON);
JArray loMessageArray = new JArray();
JObject loAddMessage;
foreach (var loMessageGroup in loMessages.Properties().GroupBy(item => Regex.Match(item.Name,#".*-(?<pos>\d+)").Groups["pos"].Value))
{
loAddMessage = new JObject();
foreach (var loMessage in loMessageGroup)
loAddMessage[loMessage.Name] = loMessage.Value.ToString();
loMessageArray.Add(loAddMessage);
}
Console.WriteLine(loMessageArray.ToString());
The Json Ouput is like this:
[
{
"message-Code-1": "000",
"msg-Number-Pos1-1": "0000",
"msg-Number-Pos2-1": "1",
"msg-Number-Pos3-1": "1"
},
{
"message-Code-2": "1",
"msg-Number-Pos1-2": "0001",
"msg-Number-Pos2-2": "2",
"msg-Number-Pos3-2": "1"
},
{
"message-Code-3": "0002",
"msg-Number-Pos1-3": "3",
"msg-Number-Pos2-3": "1",
"msg-Number-Pos3-3": "1"
},
{
"message-Code-4": "0003",
"msg-Number-Pos1-4": "3",
"msg-Number-Pos2-4": "1",
"msg-Number-Pos3-4": "1"
}
]
The DataTable contains single column EFFDATE.
EFFDATE
2015-06-15
2014-10-21
2014-07-17
2014-07-16
2014-06-17
2014-03-13
I have the following code to convert DataTable dttbl to JSON.
JsonConvert.SerializeObject(dttbl, Formatting.Indented)
The output from conversion is
[
{
"EFFDATE": "2015-06-15"
},
{
"EFFDATE": "2014-10-21"
},
{
"EFFDATE": "2014-07-17"
},
{
"EFFDATE": "2014-07-16"
},
{
"EFFDATE": "2014-06-17"
},
{
"EFFDATE": "2014-03-13"
}
]
The output I want is
{
"EFFDATE": [
"2015-06-15",
"2014-10-21",
"2014-07-17",
"2014-07-16",
"2014-06-17",
"2014-03-13"
]
}
Please advice.
var json = JsonConvert.SerializeObject(
new { EFFDATE = dt.AsEnumerable().Select(r => r[0]) }
);