当前位置:编程学习 > C#/ASP.NET >>

如何解析这种嵌套格式的JSON字符串

现在要做的是读取这个json字符串,将字符串里面的数据添加到数据库中,JSON字符串格式如下,其中只列出了两条数据:

[
    {
        "id": "154.0.0.0", 
        "date": "2013-10-08 13:05:01", 
        "temp": "17.813", 
        "battery": "3.21", 
        "datas": [
            {
                "depth": "5.0", 
                "temp": "17.38", 
                "ECe": "1371.89", 
                "WATER": "16.3"
            }, 
            {
                "depth": "10.0", 
                "temp": "17.5", 
                "ECe": "1166.14", 
                "WATER": "19.0"
            }, 
            {
                "depth": "15.0", 
                "temp": "17.62", 
                "ECe": "1282.45", 
                "WATER": "27.7"
            }, 
            {
                "depth": "20.0", 
                "temp": "17.94", 
                "ECe": "1124.01", 
                "WATER": "28.0"
            }
        ]
    }, 
    {
        "id": "154.0.0.0", 
        "date": "2013-10-08 12:05:01", 
        "temp": "17.688", 
        "battery": "3.21", 
        "datas": [
            {
                "depth": "5.0", 
                "temp": "17.31", 
                "ECe": "1357.64", 
                "WATER": "16.5"
            }, 
            {
                "depth": "10.0", 
                "temp": "17.5", 
                "ECe": "1143.47", 
                "WATER": "18.9"
            }, 
            {
                "depth": "15.0", 
                "temp": "17.62", 
                "ECe": "1282.09", 
                "WATER": "27.5"
            }, 
            {
                "depth": "20.0", 
                "temp": "18.0", 
                "ECe": "1122.95", 
                "WATER": "28.1"
            }
        ]
    }
]


我现在想对这个JSON字符串进行解析,使用dictionary 无法解析datas里面的数据。使用的以下语句:
              JavaScriptSerializer serializer = new JavaScriptSerializer();
                ArrayList arrl = serializer.Deserialize<ArrayList>(json);
                foreach (Dictionary<string, object> arr in arrl)
                {
                    foreach (string datas in arr.Keys)
                    {
                        TextBox2.Text = arr[datas].ToString();
                    }
                }
 
读不出来,但是调试过程中,arr是有值得。又试了另一种方法:
 
   Dictionary<string, object> test = (Dictionary<string,object>)serializer.DeserializeObject(json);
     object value;
     if (test.TryGetValue("datas", out value))
         TextBox2.Text = value.ToString();
 
也读不出来。
请教大家,如何读取这种JSON嵌套JSON格式的数据呢,而且可能需要遍历,因为数据量不定。有可能的话 给出代码吧。 json c# 解析 遍历 嵌套 --------------------编程问答-------------------- 引用Newtonsoft.Json.dll,下载地址:http://download.csdn.net/detail/guwei4037/5853053
class Program
    {
        static void Main(string[] args)
        {
            string json = "[{\"id\":\"154.0.0.0\",\"date\":\"2013-10-08 13:05:01\",\"temp\":\"17.813\",\"battery\":\"3.21\",\"datas\": [{\"depth\":\"5.0\",\"temp\":\"17.38\",\"ECe\":\"1371.89\",\"WATER\": \"16.3\"},{\"depth\":\"10.0\",\"temp\":\"17.5\",\"ECe\": \"1166.14\",\"WATER\":\"19.0\"},{\"depth\":\"15.0\",\"temp\":\"17.62\",\"ECe\": \"1282.45\",\"WATER\": \"27.7\"},{\"depth\": \"20.0\",\"temp\": \"17.94\",\"ECe\": \"1124.01\",\"WATER\": \"28.0\"}]}]";

            List<Data1> infoList = JsonConvert.DeserializeObject<List<Data1>>(json);

            infoList.ForEach(x => x.datas.ForEach(y => Console.WriteLine(y.temp)));//获得每一个内部temp的值
        }
    }

    public class Data1
    {
        public string id { get; set; }

        public string date { get; set; }

        public string temp { get; set; }

        public string battery { get; set; }

        public List<Data2> datas { get; set; }
    }

    public class Data2
    {
        public string depth { get; set; }

        public string temp { get; set; }

        public string ece { get; set; }

        public string water { get; set; }
    }


模拟了一条数据。 --------------------编程问答--------------------

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

public class JsonUtils {
  
  public static String encodeList(Object[] objs) {
    return encodeList(Arrays.asList(objs));
  }

  @SuppressWarnings("unchecked")
  public static String encodeList(Collection objs) {
    JSONArray list = new JSONArray();
    if (objs == null || objs.size() == 0)
      return list.toString();
    for (Object ae : objs) {
      list.add(ae);
    }
    return list.toString();
  }
  
  @SuppressWarnings("unchecked")
  public static String encodeObject(Object obj){
    if(obj instanceof Collection)
      return encodeList((Collection)obj);
    JSONObject jo = JSONObject.fromObject(obj);
    return jo.toString();
  }
  
  @SuppressWarnings("unchecked")
  public static <T>List<T> decodeList(String str, Class<T> clazz) {
    if (str == null || "".equals(str))
      return null;
    JSONArray obj = JSONArray.fromObject(str);
    Object[] rts = obj.toArray();
    List<T> result = new ArrayList<T>(rts.length);
    for (int i = 0; i < rts.length; i++) {
      Object jo = rts[i];
      T ele = (T)JSONObject.toBean((JSONObject) jo, clazz);
      result.add( ele );
    }
    return result;
  }
  
  @SuppressWarnings("unchecked")
  public static <T>T decodeObject(String json,Class<T> clz){
    JSONObject jsonObject = JSONObject.fromObject(json);
    T bean = (T) JSONObject.toBean(jsonObject, clz);
    return bean;
  }
}
--------------------编程问答--------------------  你这数据要放到几个表中啊 ? --------------------编程问答-------------------- 首先定义一个承载目标数据类型,例如
public class DataType1
{
    public string id;
    public string date;
    public DataType2[] datas;
}

public class DataType2
{
    public string depth;
}

然后直接写一行代码将json反序列化为 DataType1[] 类型的对象。

搞清楚了数据结构,你才可能写稍微复杂一点的程序。不要什么都从最低级的琐碎处开始“解析”。 --------------------编程问答-------------------- 刚看到#1已经写了基本思路。

这里要强调的不是什么技术,而是思路。那种给你写
    serializer.Deserialize<ArrayList>(json);
代码的做法,不一定适合你来学习。 --------------------编程问答--------------------
引用 4 楼 sp1234 的回复:
首先定义一个承载目标数据类型,例如
public class DataType1
{
    public string id;
    public string date;
    public DataType2[] datas;
}

public class DataType2
{
    public string depth;
}

然后直接写一行代码将json反序列化为 DataType1[] 类型的对象。

搞清楚了数据结构,你才可能写稍微复杂一点的程序。不要什么都从最低级的琐碎处开始“解析”。


我也尝试了这个结构  但是代码不一样。而且有些问题。您能帮我看看么。
 public class jsontest
    {
        
        public string id;
        public string date;
        public string temp;
        public string battery;
        public datasjson datas;
        
        
    }
    public class datasjson
    {
        public string depth0;
        public string temp0;
        public string ece0;
        public string water0;

        public string depth1;
        public string temp1;
        public string ece1;
        public string water1;

        public string depth2;
        public string temp2;
        public string ece2;
        public string water2;

        public string depth3;
        public string temp3;
        public string ece3;
        public string water3;

    }

嵌套进去的JSON格式数据是根据depth区分温度,水分的。所以我这么写,请指教。
补充:.NET技术 ,  C#
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,