JSON转换为contentvalues [英] convert JSON to contentvalues

查看:1501
本文介绍了JSON转换为contentvalues的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一个简单的方法来从一个Web服务得到JSON,并把它变成我的SQLite数据库在C#中单为Android(xamarin)?
有一些繁琐的方式做,但我想要的东西快速和优雅。

Is there an easy way to get JSON from a webservice and put it into my SQLite DB in C# mono for android (xamarin)? There are some tedious ways to do it but I want something quick and elegant.

推荐答案

我做了一个静态类,将所有对象转换为使用反射contentvalues​​。我敢肯定有一个等效的方式在Java中做到这一点。
把你的JSON对象到一个类某种这将所有属性转换成contentvalues​​。

I made a static class that will convert any object into contentvalues using reflection. I'm sure there's an equivalent way to do this in Java. Put your JSON objects into a class of some sort and this will convert all of the properties into contentvalues.

public static class Util
{
    //suck all of the data out of a class and put it into a ContentValues object for use in SQLite Database stuff
    public static ContentValues ReflectToContentValues(object o)
    {
        ContentValues cv = new ContentValues();

        foreach (var props in o.GetType().GetProperties())
        {
            object val = props.GetValue(o, null);
            //check if compatible with contentvalues (sbyte and byte[] are also compatible, but will you ever use them in an SQLite database?
            if (props.CanRead && props.CanWrite && (val is double || val is int || val is string || val is bool || val is long || val is float || val is short))
            {
                cv.Put(props.Name, val.ToString());
                Log.Info("CVLOOP", props.Name + ":" + val.ToString());
            }
            else if (val is DateTime)
                cv.Put(props.Name, ((DateTime)val).ToString("yyyy-MM-dd HH:mm:ss"));
        }

        return cv;
    }

}

这篇关于JSON转换为contentvalues的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆