0

I Get json data from third party in json format. I am trying to fetch RollId from "Id" and MType from "Data" in some cases "Data" doesn't have fields it is kind of blank.

It's working when we have "Data". In case of blank it's not working. any idea on this? Is there a better approach of doing this?

This is the Json

      string json = @"{
  'root': {
    '_type': '_container',
    'Class': '.key.PModel',
    'Elements': {
      '_type': 'array<element>',
      '_data': [
        {
          '_type': 'element',
          'Class': '.key.PElement',
          'Id': {
            '_type': 'testId',
            'Class': '.key.PModel',
            'RollId': '.key.7157'
          },
          'Data': {
            '_type': 'p_model',
            'Class': '.key.Unsupported',
            'MType': '.TestMType',
            'Version': {
              '_type': 'test__version',
              'Class': '.key.TestVersion',

            }
          }
        },
        {
          '_type': 'element',
          'Class': '.key.PElement',
          'Id': {
            '_type': 'TestId',
            'Class': '.key.PModel',
            'RollId': '.key.11261'
          },
          'Data': '.ref.root.Elements.0.Data'
        },
        {
          '_type': 'element',
          'Class': '.key.PElement',
          'Id': {
            '_type': 'TestId',
            'Class': '.key.PModel',
            'RollId': '.key.7914'
          },
          'Data': '.ref.root.Elements.0.Data'
        }

      ]
    }
  }
}";

This is the Code

public class Program
        {
            static void Main(string[] args)
            {
                //it provide json  
                var testCont = thirdpartyapi();
                var dataList = new List<TestResponse>();
                foreach (var testData in testCont.Elements())
                {
                    var data = new TestResponse();
                    data.col1 = Convert.ToInt32(testData.Id().RollId());
                    data.col2 = testData.Data().MType().ToString();
                    dataList.Add(data);
                }

            }


            public class TestResponse
            {
                public int col1 { get; set; }
                public string col2 { get; set; }


            }
        }
4
  • 2
    This JSON is invalid. Commented Jan 18, 2019 at 11:09
  • Possible duplicate of How to convert Json string to c# Class object? Commented Jan 18, 2019 at 11:11
  • @Adriani6 .. Sorry, just added the json string. Commented Jan 18, 2019 at 11:52
  • @Harshit the code you posted doesn't show what you tried. What is thirdpartyapi and Elements? Are you using a specific deserializer or is this a question about querying JSON data? Commented Jan 18, 2019 at 11:59

3 Answers 3

0

First, try to get a valid well-formed json. You can use this code beautify tool. Then you can automatically generate C# class using json2csharp. Finally as you have C# class you can apply if statements and check if property is null.

Generated C# wrapper:

public class Id
{
    public string _type { get; set; }
    public string Class { get; set; }
    public string RollId { get; set; }
}

public class Datum
{
    public string _type { get; set; }
    public string Class { get; set; }
    public Id Id { get; set; }
    public object Data { get; set; }
}

public class Elements
{
    public string _type { get; set; }
    public List<Datum> _data { get; set; }
}

public class Root
{
    public string _type { get; set; }
    public string Class { get; set; }
    public Elements Elements { get; set; }
}

public class RootObject
{
    public int encoding_version { get; set; }
    public Root root { get; set; }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! but i am trying to fetch 'RollId' and 'MType' from "Data" can we pick only these two fields?
You can actually paste the json straight into classes using built-in "Paste As Special" tool in Visual Studio.
0

If you want to pick only few fields from complex JSON, you can consider using Cinchoo ETL - an open source library

Sample below shows how to pick RollId and MType values from your json

using (var r = new ChoJSONReader("## YOUR JSON FILE PATH ##")
    .WithJSONPath("$.._data")
    .WithField("RollId", jsonPath: "$..Id.RollId", fieldType: typeof(string))
    .WithField("MType", jsonPath: "$..Data.MType", fieldType: typeof(string))
    )

{
    foreach (var rec in r)
    {
        Console.WriteLine((string)rec.RollId);
        Console.WriteLine((string)rec.MType);
    }
}

Hope it helps.

Comments

-1

The easiest way is use the DataContractJsonSerializer

Here you can read more about it.

All in all you need to create a model which has the same possible outcome as your json. Then you can just use the DataContractJsonSerializer to create an object of you model by using a MemoryStream.

Here you can find a nice tool to create the model from the JSON. For example this one:

public class Id
{
    public string _type { get; set; }
    public string Class { get; set; }
    public string RollId { get; set; }
}

public class Datum
{
    public string _type { get; set; }
    public string Class { get; set; }
    public Id Id { get; set; }
    public object Data { get; set; }
}

public class Elements
{
    public string _type { get; set; }
    public List<Datum> _data { get; set; }
}

public class Root
{
    public string _type { get; set; }
    public string Class { get; set; }
    public Elements Elements { get; set; }
}

public class RootObject
{
    public int encoding_version { get; set; }
    public Root root { get; set; }
}

Then you use the MemoryStream and the DataContractJsonSerializer to Create an object of RootObject from that JSON.

MemoryStream stream1 = new MemoryStream();  
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(RootObject));  

stream1.Position = 0;  
RootObject rootObject = (RootObject)ser.ReadObject(stream1);

And yes, as Adriani6 mentiones - your JSON is invalid at this point:

"Data": {
            "_type": "p_model",
            "Class": ".key.Unsupported",
            "MType": ".TestMType",
            "Version": {
              "_type": "test__version",
              "Class": ".key.TestVersion",

            }

There is a , at the end wich is not allowed.

3 Comments

Thanks! but i am trying to fetch 'RollId' and 'MType' from "Data" can we pick only these two fields?
DataContractSerializer isn't a good choice. It's an old implementation only meant as a stop-gap measure way back when. They way it handles dates is incompatible with the defacto standard, ISO8601. The most popular deserializer is JSON.NET which is also used in ASP.NET Web API and ASP.NET Core.
Ah okay, didn't know that. I'm not workint that much with JSON and when I do I use the DataContractSerializer. But good to know for the future!

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.