JSON,XML的解析及存储

WindowsPhone加载加载xml文件,并存入Sqlite数据库

//读取资源文件。文件为XML格式。这个文件的Building属性为Resource
StreamResourceInfo sri = Application.GetResourceStream(new Uri("/ArcDemo;component/Doc/user.xml",
UriKind.Relative));
//读取所以数据保存到String类型的result中
string result;
using (StreamReader sr = new StreamReader(sri.Stream))
{
result = sr.ReadToEnd();
}
//用XDocument类解析数据
XDocument doc = XDocument.Parse(result);
foreach (XElement item in doc.Descendants("root").Nodes())
{
//我们需要的数据在那么两个节点。Descendants就是寻找子节点。
string userid = item.Attribute("id").Value;
foreach (XElement itemnode in item.Descendants("userinfo"))
{
string username = itemnode.Element("name").Value;
string userkey = itemnode.Element("key").Value;
string la = itemnode.Element("la").Value;
string lo = itemnode.Element("lo").Value;
//把数据存入数据库
UserTable userInfo = new UserTable();
userInfo.Key = userkey;
userInfo.Name = username;
userInfo.La = la;
userInfo.Lo = lo;
db.User.InsertOnSubmit(userInfo);
}
}
//数据库提交更新
db.SubmitChanges();




解析下载后的json,并存入isolatedstorage

void wb_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            //判断是否下载成功
            if (e.Result.Length <= 0 || e.Error != null || e.Cancelled)
            {
                MessageBox.Show("获取天气预报失败!");
                return;
            }

            SelectedCity.SaveIsolated(sc);//保存更新好的城市信息

            
            JObject json = JObject.Parse(e.Result);//用Jobject解析json数据   需要引用第三方库,下载地址见文章最后
            weather = new WeatherInfo
            {
                city = (string)json["weatherinfo"]["city"],
                cityid = (string)json["weatherinfo"]["cityid"],
                date_y = (string)json["weatherinfo"]["date_y"],
                week = (string)json["weatherinfo"]["week"],
                info = (string)json["weatherinfo"]["index48_d"],
                wind1 = (string)json["weatherinfo"]["wind1"],
                temp1 = (string)json["weatherinfo"]["temp1"],
                temp2 = (string)json["weatherinfo"]["temp2"],
                temp3 = (string)json["weatherinfo"]["temp3"],
                temp4 = (string)json["weatherinfo"]["temp4"],
                temp5 = (string)json["weatherinfo"]["temp5"],
                weather1 = (string)json["weatherinfo"]["weather1"],
                weather2 = (string)json["weatherinfo"]["weather2"],
                weather3 = (string)json["weatherinfo"]["weather3"],
                weather4 = (string)json["weatherinfo"]["weather4"],
                weather5 = (string)json["weatherinfo"]["weather5"]
            };

            weather.UpdateTime = DateTime.Now;
            WeatherInfo.SaveIsolated(weather);//保存更新好的天气信息

            
        }
SaveIsolated方法

 public static void SaveIsolated(WeatherInfo w)
        {
            IsolatedStorageSettings iss = IsolatedStorageSettings.ApplicationSettings;
            iss["WeatherInfo"] = w;
        }

GetIsolated方法

public static WeatherInfo GetIsolated()
        {
            IsolatedStorageSettings iss = IsolatedStorageSettings.ApplicationSettings;
            WeatherInfo w = null;
            WeatherInfo temp = null;
            if (iss.TryGetValue("WeatherInfo", out temp))
                w = temp;
            return w;
        }

从数据库中取出数据,生成Json

using system;
  using system.collections.generic;
  using system.text;
  using system.data;
  using system.data.sqlclient;
  namespace otc.utility
  ...{
  public sealed class jsonhelper
  ...{
  /**
  /// 获取json字符串
  ///
  /// 值
  /// 数据表名
  ///
  public static string getjson(sqldatareader drvalue, string strtablename)
  ...{
  stringbuilder sb = new stringbuilder();
  sb.appendline("{");
  sb.appendline(" " + strtablename + ":{");
  sb.appendline(" records:[");
  try
  ...{
  while (drvalue.read())
  ...{
  sb.append(" {");
  for (int i = 0; i < drvalue.fieldcount; i++)
  ...{
  sb.appendformat(""{0}":"{1}",", drvalue.getname(i), drvalue.getvalue(i));
  }
  sb.remove(sb.tostring().lastindexof(’,’), 1);
  sb.appendline("},");
  }
  sb.remove(sb.tostring().lastindexof(’,’), 1);
  }
  catch(exception ex)
  ...{
  throw new exception(ex.message);
  }
  finally
  ...{
  drvalue.close();
  }
  sb.appendline(" ]");
  sb.appendline(" }");
  sb.appendline(" };");
  return sb.tostring();
  }
  }
  }
  接下来你只需要传一个sqldatareader对象就可以了。

ASP.NET MVC3中图片的 存储与取出(file,stream,byte[])

     public ActionResult SetUserImage(string id)//返回特定id的页面
        {
            var _user = from u in she.Users
                        where u.Name == id
                        select u;
            if (_user.Count() > 0)
            {
                Users us = _user.First();
                return View(us);
            }
            return View();
        }
        [HttpPost]
        public ActionResult SetUserImage(Users model)//提交后的操作
        {
            var abc = model.UserID;
            Users _user = (from u in she.Users
                           where u.UserID == model.UserID
                           select u).First();

            HttpPostedFileBase imgFile = Request.Files["imgFile"];

            string name = Request.Form["name"];

            var imgByte = new byte[imgFile.ContentLength];//数组
            imgFile.InputStream.Read(imgByte, 0, imgFile.ContentLength);//将文件以流的形式读入数组
            _user.Photo = imgByte;//存入数据库
            try
            {
                she.SaveChanges();
            }
            catch (Exception ex)
            {
                ViewBag.abc = ex.ToString();
                return View();
            }
            return RedirectToAction("SetUserImage");
        } 
获取文件方法

 public ActionResult GetUserImage(Guid id)
        {
            var imgByte = she.Users.Find(id).Photo;
            return new FileContentResult(imgByte, "image/jpeg");
        }


C#中json与任意类型的转化

 	private string ConvertObjectToJsonString(object objectToSerialize)
       {
           using (MemoryStream ms = new MemoryStream())
            {
                DataContractJsonSerializer serializer = new DataContractJsonSerializer(objectToSerialize.GetType());
                serializer.WriteObject(ms, objectToSerialize);
                ms.Position = 0;
               using (StreamReader sr = new StreamReader(ms))
                {
                    return sr.ReadToEnd();
                }
            }
      }

        private T ConvertJsonStringToObject<T>(string stringToDeserialize)
        {
            using (MemoryStream ms = new MemoryStream())
          {
                byte[] bytes = UnicodeEncoding.Unicode.GetBytes(stringToDeserialize);
                ms.Write(bytes, 0, bytes.Length);
               ms.Position = 0;
//                DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
                return (T)serializer.ReadObject(ms);
           }
        }


http://json.codeplex.com/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值