Search code examples
c#json.netkairosdb

Create Json for KairosDB api


I want to send data to KairosDB with post method but my Json is not correct. The Json must be like that:

{
    "name":"Hermle_1",
    "datapoints":[
        [
            "1530710258000",
            23.0
        ],
        [
            "1530710257000",
            21.0
        ]
    ],
    "tags":{
        "SensorName":"capteur_temperature"
    }
}

For datapoints I add Dictionary<string, float> to my object. What I have when I serialize it:

{
    "name":"Hermle_1",
    "datapoints":{
        "1530710258000":23.0,
        "1530710257000":21.0
    },
    "tags":{
        "SensorName":"capteur_temperature"
    }
}

If I change my dictionary .ToArray() I have this Json:

{
    "name":"Hermle_1",
    "datapoints":[
        {
            "Key":"1530710258000",
            "Value":23.0
        },
        {
            "Key":"1530710257000",
            "Value":21.0
        }
    ],
    "tags":{
        "SensorName":"capteur_temperature"
    }    
}

I don't know how to generate json in the expected format for the datapoints.

EDIT : How I create my object:

dynamic jsonObj = new ExpandoObject();
jsonObj.name = sd.Engine_name;

Dictionary<string, float> datapoints = new Dictionary<string, float>();
Dictionary<string, string> tags = new Dictionary<string, string>();

tags.Add("SensorName", sensor.Name);

//.........
while (reader.Read())
{    
    datapoints.Add(Convert.ToString(reader["time"]),
    Convert.ToSingle(reader["value"]));
}
//....
jsonObj.datapoints = datapoints;
jsonObj.tags = tags;

string a = JsonConvert.SerializeObject(jsonObj, Formatting.Indented);

Solution

  • As I said in my comment above, datapoints is not a Dictionary but a List<List<object>> It must be object because you have to put string and float into the same list.

    List<List<object>> datapoints = new List<List<object>>();
    while (reader.Read()) {
        datapoints.Add(new List<object>{
            Convert.ToString(reader["time"]), 
            Convert.ToSingle(reader["value"])
        });
    }