logo
down
shadow

Flattening out a JToken


Flattening out a JToken

By : user2955378
Date : November 22 2020, 10:40 AM
will help you The hierarchy of objects in Json.NET can be rather deep. A rough guide can be found in this answer.
To solve your problem, you first need an extension method to take the properties of a JObject and return then in a collection with a name prefix:
code :
public static class JsonExtensions
{
    public static IEnumerable<KeyValuePair<string, JToken>> FlattenFields(this JObject obj, string prefix)
    {
        foreach (var field in obj)
        {
            string fieldName = prefix + "_" + field.Key;
            var fieldValue = field.Value;
            yield return new KeyValuePair<string, JToken>(fieldName, fieldValue);
        }
    }
}
public static class JsonExtensions
{
    public static IEnumerable<T> Yield<T>(this T item)
    {
        yield return item;
    }

    public static JToken EditFields(this JToken token, Func<KeyValuePair<string, JToken>, IEnumerable<KeyValuePair<string, JToken>>> editor)
    {
        if (token == null)
            return null;
        switch (token.Type)
        {
            case JTokenType.Array:
                return EditFields((JArray)token, editor);
            case JTokenType.Object:
                return EditFields((JObject)token, editor);
            default:
                return token;
        }
    }

    static JToken EditFields(JArray array, Func<KeyValuePair<string, JToken>, IEnumerable<KeyValuePair<string, JToken>>> editor)
    {
        JArray newArray = null;
        foreach (var element in array)
        {
            var newElement = EditFields(element, editor);
            if (newElement != null)
            {
                if (newArray == null)
                    newArray = new JArray();
                newArray.Add(newElement);
            }
        }
        return newArray;
    }

    static JToken EditFields(JObject obj, Func<KeyValuePair<string, JToken>, IEnumerable<KeyValuePair<string, JToken>>> editor)
    {
        JObject newObj = null;

        foreach (var field in obj)
        {
            foreach (var newField in editor(field))
            {
                if (newObj == null)
                    newObj = new JObject();
                newObj[newField.Key] = newField.Value.EditFields(editor);
            }
        }

        return newObj;
    }
}
public static class JsonExtensions
{
    public static JToken PromoteNamedPropertiesToParents(this JToken token, string propertyName)
    {
        return token.EditFields(pair =>
        {
            if (pair.Key == propertyName && pair.Value is JObject)
            {
                return ((JObject)pair.Value).FlattenFields(pair.Key);
            }
            return pair.Yield();
        });
    }
}
public static class TestFlatten
{
    public static void Test()
    {
        string jsonString = @"{
            ""data"": [
                {
                    ""company"": {
                        ""ID"": ""12345"",
                        ""location"": ""Some Location""
                    },
                    ""name"": ""Some Name""
                }
            ]
        }";
        JObject obj = JObject.Parse(jsonString);
        var newObj = (JObject)obj.PromoteNamedPropertiesToParents("company");
        Debug.WriteLine(newObj);
    }
}
{
  "data": [
    {
      "company_ID": "12345",
      "company_location": "Some Location",
      "name": "Some Name"
    }
  ]
}


Share : facebook icon twitter icon
Adding new Jtoken to Json Jtoken

Adding new Jtoken to Json Jtoken


By : Anita Tadge
Date : March 29 2020, 07:55 AM
I wish did fix the issue. Unless the ordering really matters, I suspect you just want to make it another property of the error:
code :
// Variable names edited to follow normal C# conventions
var jsonResponse = JObject.Parse(response);
jsonResponse["error"]["retryMessage"] = "Unknown";
{
  "error": {
    "errors": [
      {
        "domain": "global",
        "reason": "required",
        "message": "Login Required",
        "locationType": "header",
        "location": "Authorization"
      }
    ],
    "code": 401,
    "message": "Login Required",
    "retryMessage": "Unknown"
  }
}
How to convert a JToken

How to convert a JToken


By : Dharan Dharan
Date : March 29 2020, 07:55 AM
wish of those help You can use the JToken.ToObject() method.
code :
JToken token = ...;
int value = token.ToObject<int>();
Can't get value from JTOken

Can't get value from JTOken


By : Samuel Derbyshire
Date : March 29 2020, 07:55 AM
wish of those help To convert the value to a defined type you could use one of the defined methods below:
code :
System.Convert.ChangeType(jtoken.ToString(), targetType);
JsonConvert.DeserializeObject(jtoken.ToString(), targetType);
string json = @{"DE:Actual Savings": 42217.0}
var obj = (JObject)JsonConvert.DeserializeObject(json);
Type type = typeof(float);
var i1 = System.Convert.ChangeType(obj["DE:Actual Savings"].ToString(), type);
Flattening a pack of types, where non-type values are part of the flattening

Flattening a pack of types, where non-type values are part of the flattening


By : Erick Reyes
Date : March 29 2020, 07:55 AM
this one helps. The task becomes feasible if each non-type parameter (unpacked from, say, an std::index_sequence) can be wrapped in its own std::integral_constant. Then there are only type template parameters at the level where the flattening occurs and one may use a simple type container like template struct Types {};.
code :
// upper version for shorter type names; lower version for showing types
template<auto v> struct Val : std::integral_constant<decltype(v), v> {};
//template<auto v> using Val = std::integral_constant<decltype(v), v>;
// NOTE: bug(?) in GCC 7.2 which maps size_t(0) to false and size_t(1) to true

template<class I, I... is>
auto flatten(Type< std::integer_sequence<I, is...> >) {
  return Flattened<Val<is>...>{};
}
#include <iostream>
#include <tuple>
#include <utility>

// upper version for shorter type names; lower version for showing types
template<auto v> struct Val : std::integral_constant<decltype(v), v> {};
//template<auto v> using Val = std::integral_constant<decltype(v), v>;
// NOTE: bug(?) in GCC 7.2 which maps size_t(0) to false and size_t(1) to true

template<size_t... is, class F>
constexpr decltype(auto) indexer_impl(std::index_sequence<is...>, F f) {
  return f(Val<is>{}...);
}

template<size_t size, class F>
constexpr decltype(auto) indexer(F f) {
  return indexer_impl(std::make_index_sequence<size>{}, f);
}

////////////////////////////////////////////////////////////////////////////////

template<class T_>
struct Type {};

template<class... Ts>
struct Types {
  static constexpr auto size = Val<sizeof...(Ts)>{};
  using Tuple = std::tuple<Ts...>;
};

template<size_t i, class T>
using at_t = std::tuple_element_t<i, typename T::Tuple>;

////////////////////////////////////////////////////////////////////////////////

template<class...> struct Flattened;

template<class I, I... is> using int_seq = std::integer_sequence<I, is...>;

// specify which types are allowed in a flat type container
template<class T> struct is_flat : Val<true> {};
template<class I, I... is> struct is_flat< int_seq<I, is...> > : Val<false> {};
template<class... Ts> struct is_flat< Types<Ts...> > : Val<false> {};
template<class... Ts> struct is_flat< Flattened<Ts...> > : Val<false> {};

// check if a type is an instantiation of `template<class...> struct Flattened`
template<class T> struct is_flattened : Val<false> {};
template<class... Ts> struct is_flattened<Flattened<Ts...>> : Val<true> {};

// specific type container which guarantees to contain `is_flat` types only
template<class... Ts> struct Flattened : Types<Ts...> {
  static_assert((... && is_flat<Ts>{}));
};

////////////////////////////////////////////////////////////////////////////////

namespace internal {

auto merge() {
  return Flattened<>{};
}

template<class... Ts>
auto merge(Flattened<Ts...> done) {
  return done;
}

template<class... Ts, class... Us>
auto merge(Flattened<Ts...>, Flattened<Us...>) {
  return Flattened<Ts..., Us...>{};
}

// merge more than two args: attempt to avoid linear recursion: is it better?
template<class... Ts, class... Fs>
auto merge(Flattened<Ts...>, Fs...) {
  static_assert((... && is_flattened<Fs>{}));

  using T = Types<Flattened<Ts...>, Fs...>;

// group the Flattened args into two halves
  constexpr size_t N = T::size;
  constexpr size_t N0 = N/2u;
  constexpr size_t N1 = N-N0;

  auto h0 = indexer<N0>([] (auto... is) { return merge(at_t<is, T>{}...); });
  auto h1 = indexer<N1>([] (auto... is) { return merge(at_t<N0+is, T>{}...); });

  return merge(h0, h1);
}

template<class T>
auto flatten(Type<T>) {
  static_assert(is_flat<T>{});
  return Flattened<T>{};
}

template<class I, I... is>
auto flatten(Type< std::integer_sequence<I, is...> >) {
  return Flattened<Val<is>...>{};
}

template<class... Ts>
auto flatten(Type< Types<Ts...> >) {
  return merge(internal::flatten(Type<Ts>{})...);
}

}// internal

template<class... Ts>
auto flatten(Types<Ts...>) {
  return internal::merge(internal::flatten(Type<Ts>{})...);
}

////////////////////////////////////////////////////////////////////////////////

template<class T>
void inspect() {
  std::cout << __PRETTY_FUNCTION__ << std::endl;
}

struct Custom {};

int main() {
  auto foo = Types<
    Types<int, char, long>,
    Val<7>,
    Types<double, Val<5>, float, Types<unsigned, Types<Custom, Types<char>, int>>, std::make_index_sequence<4u>>,
    std::index_sequence<5u,19u,4u>,
    Types<>,
    Val<8>
  >{};

  auto bar = flatten(foo);
  inspect<decltype(bar)>();

  return 0;
}
void inspect() [with T = Flattened<int, char, long int, Val<7>, double, Val<5>, float, unsigned int, Custom, char, int, Val<false>, Val<true>, Val<2>, Val<3>, Val<5>, Val<19>, Val<4>, Val<8> >]
void inspect() [with T = Flattened<int, char, long int, std::integral_constant<int, 7>, double, std::integral_constant<int, 5>, float, unsigned int, Custom, char, int, std::integral_constant<bool, false>, std::integral_constant<bool, true>, std::integral_constant<long unsigned int, 2>, std::integral_constant<long unsigned int, 3>, std::integral_constant<int, 5>, std::integral_constant<long unsigned int, 19>, std::integral_constant<long unsigned int, 4>, std::integral_constant<int, 8> >]
Difference between JToken.ToObject<T>() vs JToken.Value<T>()

Difference between JToken.ToObject<T>() vs JToken.Value<T>()


By : user3246759
Date : March 29 2020, 07:55 AM
I hope this helps you . What is the difference between the JToken.ToObject() method and the JToken.Value() extension method (the one without the key parameter)? , The difference is as follows:
Related Posts Related Posts :
  • Console application doesn't obey Thread.Join
  • System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
  • Creating a scripting environment for a C# program
  • Is it reasonable to replace .Equals with a method rather than override it?
  • How I can capture multiple keys?
  • How to have all my classes default functionalities like .ToString method
  • Business Object properties: model as Objects or Enums?
  • Loading this assembly would produce a different grant set from other instances
  • How to call a method without first calling it's constructor in C#
  • Can't set a date time in one of my entity framework objects, says NullReferenceException
  • GETJob() Win32 Print spooler api 64bit The parameter is incorrect, how to fix?
  • Switch Case Causing Trouble In Going To A particular Function
  • Switch Case Calling A Function Based On The User's Choice
  • Accessing WebBrowser on different Threads
  • CPU Usage Avoid 100% With Environment.ProcessorCount?
  • Select distinct categories from database
  • C# app getting Watson dialog when calling TerminateProcess
  • The underlying provider failed on Open in entity framework connection
  • Compile a library without checking references
  • Can we create and access a registry key in HKEY_LOCAL_MACHINE without running application with admin permissions in C#
  • Control light intensity with a UI slider
  • Threading (Does these threads exits or aborts itself?)
  • Change the function of a button if Logged in
  • how to accept value in date format in textbox in C# windows form?
  • remove the lines from RichtextBox?
  • How to call String.Split that takes string as separator?
  • Specify task timeout in parallel linq to objects
  • comparing two custom objects to prevent duplicates
  • How to Print Text from ComboBox into a MessageBox
  • How can I do a Func<object[],Expression<Func<T,bool>>> dynamic?
  • C# SqlDataReader No data exists for the row/column
  • My code is not giving the desired output
  • Is it possible to have multiple MVC routes point to the same controller/view?
  • Updating Listbox results in " Invalid cross-thread access."
  • Finding Elbow Angle with Kinect
  • Host a mvc web api application in the sub-folder of a website
  • How to generate a sequential unique id in a thread-safe way
  • How to add a separator to a WPF combobox that is databound?
  • optimize linq query with related entities
  • Optimize this code for large input
  • Is there any way to clear all list box short way?
  • ACR122 Device Programming sample does not find reader
  • Parallel Library: does a delay on one degree of parallelism delay all of them?
  • How to convert a var which contains Long to an Long[]
  • Quickly prune and create valid data combinations
  • Get 3 parameters out of a Dictionary<string, Dictionary<string Action>>
  • Regex IsMatch taking too long to execute
  • Shuffling divs using C# behindcode
  • ASP.NET Project and IE10 Compatibility Mode issues in Windows 7
  • Why can't I loop through this dictionary?
  • RavenDB Stream for Unbounded Results - Connection Resilience
  • How to remove the focus border of a CheckBox in C# Visual Studio?
  • Exception while using String.Format "Index (zero based) must be greater than or equal to zero and less than the siz
  • Caching an LDAP connection
  • C# How to detect kill event sender
  • How to Display Splashscreen and login form at same time using c#
  • Read .sql script with parameters
  • Why would I need to compile/generate methods/code at runtime?
  • Unable to create a constant value of type 'Project.Models.Subcategory'. Only primitive types or enumeration types are su
  • How to run possibly synchronous or possibly asynchronous code?
  • shadow
    Privacy Policy - Terms - Contact Us © ourworld-yourmove.org