Свойства С помощью [JsonConverter (typeof (StringEnumConverter))] Не устанавливается как строка в схеме [дубликат]

Мне нужно создать веб-сервер

Да. Вам нужно место, где вы можете сопоставить имя / адрес электронной почты с регистрационными идентификаторами. Эти идентификаторы регистрации должны быть включены в запрос в FCM, например

{
    'registration_ids': ['qrgqry34562456', '245346236ef'],
    'notification': {
        'body': '',
        'title': ''
    },
    'data': {

    }
}

отправит push на «qrgqry34562456» и «245346236ef».

Идентификатор регистрации, который вы используете в вызов - это тот, который называется «токен» в этом обратном вызове в приложении.

public class MyService extends FirebaseInstanceIdService {
    @Override
    public void onTokenRefresh() {
    }
}
3
задан Tom 9 September 2014 в 09:44
поделиться

2 ответа

У меня была та же проблема. Я написал хак, который заменяет целые числа с перечислениями через отражение. Все еще ждут официального исправления.

var jsonSchemaString =  JsonUtility.getRawJSONSchema(typeof(Class1).FullName);

Не тестируется во всех тестовых случаях.

public class JsonUtility
{
    public static string getRawJSONSchema(string jsonObjectTypeName)
    {
        var jsonSchemaGenerator = new JsonSchemaGenerator();

        var myType = Type.GetType(jsonObjectTypeName);

        var schema = jsonSchemaGenerator.Generate(myType);

        schema.Title = myType.Name;

        var enumToFix = new Dictionary<string, string>();

        FindEnums(schema, myType, ref enumToFix);

        var writer = new StringWriter();

        var jsonTextWriter = new JsonTextWriter(writer);

        schema.WriteTo(jsonTextWriter);

        var result = writer.ToString();

        ReplaceEnums(ref result, enumToFix);

        return result;
    }



    //This is a known issue with JsonSchemaGenarator
    //Stay tuned with future releases of JSON.Net package
    //Enums are generator as integers
    //Lets convert intergers to string here
    private static void FindEnums(JsonSchema schema, Type Type, ref Dictionary<string, string> result)
    {

        if (schema.Properties != null)
            foreach (var prop in schema.Properties)
            {
                if (prop.Value.Enum != null)
                {

                    var properties = Type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
                    foreach (var p in properties)
                    {
                        SearchProperty(p, prop.Key, ref result);
                    }


                }
                FindEnums(prop.Value, Type, ref result);
            }

    }



    private static void SearchProperty(PropertyInfo property, string propertyName, ref Dictionary<string, string> result)
    {
        //IF property name is same as JSON property name
        if (property.Name.Trim().ToLower() == propertyName.Trim().ToLower())
        {
            result.Add(property.Name, EnumToJsonArray(property.PropertyType));
            return;
        }
        //Custom JSON property names set via attributes
        foreach (CustomAttributeData customAttr in property.CustomAttributes)
        {
            if (customAttr.AttributeType.Name == "JsonPropertyAttribute")
            {
                foreach (CustomAttributeNamedArgument arg in customAttr.NamedArguments)
                {
                    if (arg.TypedValue.Value.ToString().Trim().ToLower() == propertyName.Trim().ToLower())
                    {
                        result.Add(propertyName, EnumToJsonArray(property.PropertyType));
                        return;
                    }
                }
                foreach (CustomAttributeTypedArgument arg in customAttr.ConstructorArguments)
                {
                    if (arg.Value.ToString().Trim().ToLower() == propertyName.Trim().ToLower())
                    {
                        result.Add(propertyName, EnumToJsonArray(property.PropertyType));
                        return;
                    }
                }
            }
        }



        PropertyInfo[] info = property.PropertyType.GetProperties(BindingFlags.Public | BindingFlags.Instance);

        if (info.Length > 0)
        {
            foreach (var item in info)
            {
                SearchProperty(item, propertyName, ref result);
            }
        }

    }

    private static string EnumToJsonArray(Type type)
    {
        if (!type.IsEnum)
            throw new InvalidOperationException("enum expected");

        var results =
            Enum.GetValues(type).Cast<object>().Select(enumValue => enumValue.ToString())
                .ToList();

        return Newtonsoft.Json.JsonConvert.SerializeObject(results);

    }

    private static void ReplaceEnums(ref string result, Dictionary<string, string> enumToFix)
    {
        foreach (var item in enumToFix)
        {
            result = Regex.Replace(result, @"""" + item.Key + ".*?}", @"""" + item.Key + @""":{""required"":true,""type"":""string"",""enum"":" + item.Value + @"}");
        }
    }

}
1
ответ дан justcoding121 25 August 2018 в 19:59
поделиться

Установите пакет Newtonsoft.Json.Schema через диспетчер пакетов NuGet, тогда вы можете выводить перечисления в виде строк из коробки.

Указанные классы

public class Foo
{
    public Options Bar { get; set; }
}

public enum Options 
{
    Option1,
    Option2
}

Схема будет сгенерированный следующим образом, не нужно украшать классы / свойства атрибутом [JsonConverter(typeof(StringEnumConverter))].

JSchemaGenerator generator = new JSchemaGenerator();
generator.GenerationProviders.Add(new StringEnumGenerationProvider());
JSchema schema = generator.Generate(typeof(Foo), false);
//Console.WriteLine(schema);

3
ответ дан Mikko Viitala 25 August 2018 в 19:59
поделиться
Другие вопросы по тегам:

Похожие вопросы: