0

Basically, I want to do a method that create and return an generic object (C#) with the two fields of the JSON

Object

{"value": 1, "type": "int"}
{"value": "true", "type": "boolean"}
{"value": "dfsfd", "type": "string"}
{"value": "31/03/2020", "type": "datetime"}
Patrick Mcvay
  • 2,221
  • 1
  • 11
  • 22
Flávio Jardim
  • 175
  • 1
  • 10
  • Thats not valid JSON – RoadRunner Mar 31 '20 at 16:29
  • 1) That looks like [newline delimited JSON](http://ndjson.org/) not JSON. 2) Could you clarify your question please? You wrote *i want to do a method that create and return an object with the two fileds of the JSON* but it's hard to understand what you mean by that. Also, your JSON sample looks odd, `{"value": "sds", "type": "boolean"}` claims to be boolean but `"sds" is a string not a boolean. Can you please [edit] your question your question to show real input data and the desired real output data? As it is, your question might get closed as needing clarification. – dbc Mar 31 '20 at 16:31
  • {"value": "sds", "type": "boolean"} its the object. The idea is to transform a json into an object – Flávio Jardim Mar 31 '20 at 16:40
  • What do you mean by *The idea is to transform a json into an object*? `{"value": "true", "type": "boolean"}` is already a JSON object. Are you just looking for [How can I parse JSON with C#?](https://stackoverflow.com/a/17842600/3744182)? – dbc Mar 31 '20 at 16:52
  • The idea its receive a json a return an oject with the two fields, Value and Type. – Flávio Jardim Mar 31 '20 at 17:00

1 Answers1

3

Your JSON is formatted wrong for one. It should look more like below.

Option 1:

{ "Classes": [
    {"value": "sdasd", "type": "int"},
    {"value": "sds", "type": "boolean"},
    {"value": "sd", "type": "string"},
    {"value": "sdds", "type": "datetime"}
]}

This is an object array in JSON. If this is the newline delimited JSON, honestly, I have no idea about that.

Next you will have to create a class that you will deserialize this JSON into.

public class CollectionOfMyClass
{
    public List<MyClass> Classes { get; set; }
}

public class MyClass
{
    public object Value { get; set; }
    public object Type { get; set; }
}

Then to deserialize using Newtonsoft.Json

    public CollectionOfMyClass GetCollection(string jsonString)
    {
        return Newtonsoft.Json.JsonConvert.DeserializeObject<CollectionOfMyClass>(jsonString);
    }

Option 2: this is a more generic approach

Json:

[
    {"value": "sdasd", "type": "int"},
    {"value": "sds", "type": "boolean"},
    {"value": "sd", "type": "string"},
    {"value": "sdds", "type": "datetime"}
]

Deserializing with Newtonsoft.JSON:

    public List<Dictionary<object, object>> GetCollection1(string jsonString)
    {
        return Newtonsoft.Json.JsonConvert.DeserializeObject<List<Dictionary<object, object>>>(jsonString);
    }
Patrick Mcvay
  • 2,221
  • 1
  • 11
  • 22