2

I am using Newtonsoft.JSON to serialize a DataTable into a single JSON payload.

The resulting payload looks like:

[
    {
        "Name" : "Example_Name_1",
        "Value": "Example Value 1"
    },
    {
        "Name" : "Example_Name_2",
        "Value": "Example Value 2"
    },...
]

For use with an external library, I need it to like:

[
    {
        "Name" : "Example_Name_1",
        "Value": {
            "Value": "Example Value 1"
        }
    },
    {
        "Name" : "Example_Name_2",
        "Value": {
            "Value": "Example Value 2"
        }
    },...
]

Is the any way to make this transformation? I've been looking at Regular Expressions, but haven't had any luck.

I've been playing with different regex patterns and I saw another SO solution that was similar, but used JavaScript Mappings?

var strJson = "[{\"Name\": \"Example_Name_1\",\"Value\": \"Example Value 1\"}]";

var pattern = "{\"Name\": \"*\",\"Value\": \"*\"}";
var replacement = "{\"Name\": \"*\",\"Value\": {\"Value\": \"*\"}}";
var input = strJSON;
var result = Regex.Replace(input, pattern, replacement);

return result;

[EDIT] The DataTable has just 2 columns: Property_Name, & Property_Value I'm serializing it with

    JsonConvert.SerializeObject(myDataTable);
2
  • Please provide serialization code too Commented Sep 3, 2019 at 20:43
  • @ingvar 'JsonConvert.SerializeObject(myDataTable);' Commented Sep 3, 2019 at 20:55

3 Answers 3

3

I would probably use LINQ to transform the datatable to your preferred format. You didn't provide the actual datatable, but the transformation would be something like this:

IEnumerable<Data> yourData = GetData();

var transformedData = yourData.Select(d => new {
    Name = d.Name,
    Value = new {
        Value = d.Value
    }
});

string json = JsonConvert.SerializeObject(transformedData);

The json variable should now (hopefully) be in the format you want without needing to use regex.

Sign up to request clarification or add additional context in comments.

Comments

2

Take a look at the Newtonsoft.Json.Linq namespace. It contains classes like JObject, JArray, and JToken to achieve what you're trying to do.

Here's a short snippet to start you along:

var strJson = "[{\"Name\": \"Example_Name_1\",\"Value\": \"Example Value 1\"}]";
var newObject = JArray.Parse(strJson);
for(int i = 0; i < newObject.Count; i++)
{
    newObject[i]["Value"] = new JObject()
    {
        { "Value", newObject[i]["Value"] }
    };
}

You can iterate through the Descendants of the original JObject looking for the key "Value", or something else, to convert it from a string to a JObject, like my code sample.

3 Comments

System.ArgumentException: 'Can not add Newtonsoft.Json.Linq.JValue to Newtonsoft.Json.Linq.JObject.'
@Rhystic, I updated the answer so it works correctly. This time I tested the code :)
to get a minified Json string, I added: return newObject.ToString(Formatting.None);
2

You can just parse the response into json and loop through the data to create a new object. Please check out the code which i created using your sample data.

var runCode = function(){
  var strJson = "[{\"Name\": \"Example_Name_1\",\"Value\": \"Example Value 1\"},{\"Name\": \"Example_Name_2\",\"Value\": \"Example Value 2\"}]";
  parsedJson = JSON.parse(strJson)
  new_json = []
  for (var i = 0; i < parsedJson.length; i++) {
    temp_json = {}
    temp_json['Name'] = parsedJson[i]['Name']
    temp_json['Value'] = {
      'Value': parsedJson[i]['Value']
    }
    new_json.push(temp_json)
  }
  console.log(new_json)
}

runCode()

2 Comments

The snipped looks like it works great. Would you mind converting it to a C# function please?
@Rhystic sorry for that but i do not have a good knowledge of c#. But you can use this logic to loop through the json. All you need to do is loop through the json and store the value in a temp dictionary and then append it to a list

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.