Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to manually parse a JSON string in net-core 2.0

I have a json string with the following structure

{
    "resource": "user",
    "method": "create",
    "fields": {
        "name": "John",
        "surname: "Smith",
        "email": "[email protected]"
    }
}

The keys inside fields are variable, that means I don't know them in advance

So, instead of deserializing a json string to an object, I need to traverse the json, in order to get the properties inside fields in a Dictionary or something like that.

I heard about the Json.NET library and it's ability to parse dynamic jsons, but I'm not sure it it's already included in net-core or not.

What would be the standard / easiest way to accomplish that in net-core 2.0. Code example would be appreciated.

like image 240
opensas Avatar asked Sep 04 '17 03:09

opensas


People also ask

How do I parse a string in JSON?

Use the JavaScript function JSON.parse() to convert text into a JavaScript object: const obj = JSON.parse('{"name":"John", "age":30, "city":"New York"}'); Make sure the text is in JSON format, or else you will get a syntax error.

How do I deserialize JSON in .NET core?

NET objects (deserialize) A common way to deserialize JSON is to first create a class with properties and fields that represent one or more of the JSON properties. Then, to deserialize from a string or a file, call the JsonSerializer. Deserialize method.

What is JSON parse in C#?

Introduction to JSON Parser in C# JSON (JavaScript Object Notation) parse is language-independent which is a lightweight data-interchanging format, self-describing, and easy to understand. JSON parser is an alternative to XML it represents objects in structural text format and the data stored in key-value pairs.

Is JSON easy to parse?

JSON is a data interchange format that is easy to parse and generate. JSON is an extension of the syntax used to describe object data in JavaScript. Yet, it's not restricted to use with JavaScript. It has a text format that uses object and array structures for the portable representation of data.


1 Answers

Yes. You can add Newtonsoft.json package to your .net core project. And to query the dynamic json object, you can use the JObject object provided by the library to parse your json into a dynamic object. Here is the link for the document.

Given your json sample it may look like this

 var resource = JObject.Parse(json);
 foreach (var property in resource.fields.Properties())
 {
   Console.WriteLine("{0} - {1}", property.Name, property.Value);
 }
like image 75
Jaya Avatar answered Sep 20 '22 16:09

Jaya