English 中文(简体)
在使用纽顿软的团结中将JSON降为三角结构的问题。 Json
原标题:Issue with deserializing JSON into Trie structure in Unity using Newtonsoft.Json

我有18个名为<条码>的JsonFileAsset的JSON档案,是具有以下特征的Trie结构的典型词典:

- "@" represents the end of a string.
- "#" represents children nodes in the Trie.
- "$" represents  true , indicating the end of a word.
- "%" represents  false , indicating not the end of a word."

在JSON档案中:

{"@":"%","#":{"a":{"@":"%","#":{"a":{"@":"%","#":{"h":{"@":"$","#":{"e":{"@":"%","#":{"d": ...

Here is the code that I tried to make the deserialization process work on TrieHandler:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Newtonsoft.Json;

public class TrieHandler
{
    private Dictionary<string, object> trieDict;

    public void LoadTrieFromJson(string jsonContent)
    {
        trieDict = JsonConvert.DeserializeObject<Dictionary<string, object>>(jsonContent);
        if (trieDict == null)
        {
            Debug.LogError("Failed to parse JSON content: " + jsonContent);
        }
        Debug.Log("TrieDict size: " + trieDict.Count);
    }


    public bool IsWordValid(string word)
    {
        return IsWordInTrie(trieDict, word, 0);
    }

    private bool IsWordInTrie(Dictionary<string, object> node, string word, int index)
    {
        if (index == word.Length)
        {
            // Check if the current node represents the end of a word
            return node.ContainsKey("@");
        }

        char currentChar = word[index];

        if (!node.ContainsKey("#"))
            return false; // No children, word does not exist

        Dictionary<string, object> childrenDict = (Dictionary<string, object>)node["#"];

        if (!childrenDict.ContainsKey(currentChar.ToString()))
            return false; // Current character is not present in children

        return IsWordInTrie(childrenDict[currentChar.ToString()] as Dictionary<string, object>, word, index + 1);
    }
}

public class GameplayController : MonoBehaviour
{
    public string selectedTileLetters = "";

    // Trie handler instance
    private TrieHandler trieHandler;
    private string jsonContent;

    void Start()
    {
        trieHandler = new TrieHandler();
        TextAsset jsonFile = Resources.Load<TextAsset>("JsonFileAsset");
        if (jsonFile != null)
        {
            trieHandler.LoadTrieFromJson(jsonFile.text);
        }
        else
        {
            Debug.LogError("Failed to load JSON file");
        }
    }
    ... // Rest of the code not shown
}

我试图利用“团结”的本地Json通用工具,将Json资产储存在资源名录上。 trieDict = JsonUtility.FromJson<Dictionary<string, Object>>jsonContent),但trieDict.Count向我扔下了一张<0。 如果我尝试使用<代码>纽顿软。 Json s JsonConvert.DeserializeObject 然后,我拿到<代码>trieDict.Count>>。 然而,由于我的<代码>JsonFileAsset文档中含有400k+关键值的配对器,并且<代码>trieDict.Count应当印制更多份。 在该方案的其他部分,IsordValid方法从来未退回Tru boolean,我已经测试了我的Trie 读物算法,并做了完全的细微工作,使问题仅与分离。 LoadTrieFromJson sfally deserialization process.

我应当做些什么来确定<代码>的脱硫过程。 LoadTrieFromJson with Newtonsoft.Json ?

问题回答

总的来说,在您的帝国化目标中,当你有<条码>、目标JObject或类似的条目。 虽然你可能这样做,以建立你的实际三角结构,但这项工作范围很广。

如果我正确理解你的结构,以及它是如何在“智者”档案中代表的,那么你就应当能够读到该档案中,例如(使用<条码>。

class SerializedTrieNode
{
    [JsonPropertyName("@")]
    public char EOS { get; set; } =  % ;
    
    [JsonIgnore]
    public bool IsEndOfString => EOS ==  $ ;
    
    [JsonPropertyName("#")]
    public Dictionary<char, SerializedTrieNode>? Children { get; set; }
    
    [JsonIgnore]
    public int NodeCount => (Children?.Values.Sum(node => node.NodeCount) ?? 0) + 1;
    
    public bool Contains(ReadOnlySpan<char> chars)
    {
        if (chars.Length == 0)
            return IsEndOfString;
        if (Children is null || !Children.TryGetValue(chars[0], out var next))
            return false;
        return next.Contains(chars[1..]);
    }
}

I ve thrown a recursive Contains method in there to give you an idea of how you can use this to search for a valid word, but no guarantees as to the speed and it s case sensitive.

无论如何,请举一个样本,看它所看的是什么。

首先,JSON数据以“on”、“one”和“once”的“on:

{"@":"%","#":{"o":{"@":"%","#":{"n":{"@":"$","#":{"e":{"@":"$"},"c":{"@":"%","#":{"e":{"@":"$"}}}}}}}}}

现在有两处试验:

SerializedTrieNode rootNode = JsonSerializer.Deserialize<SerializedTrieNode>(File.ReadAllText("sample.json"));

// Words we added
Console.WriteLine(rootNode.Contains("on"));     // true
Console.WriteLine(rootNode.Contains("one"));    // true
Console.WriteLine(rootNode.Contains("once"));   // true

// Partials should not match
Console.WriteLine(rootNode.Contains("o"));      // false
Console.WriteLine(rootNode.Contains("onc"));    // false

// Extras should not match
Console.WriteLine(rootNode.Contains("onto"));   // false

// Case matters
Console.WriteLine(rootNode.Contains("Once"));   // false

当然,这当然应该正确分类。 它只是写“<代码”的简单任务。 如果你想重建你的初等人物档案,添加方法。





相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

热门标签