从CSV或数据库生成JSON数组

时间:2014-06-09 17:03:12

标签: asp.net arrays json web-services csv

我希望从CSV或数据库创建一个JSON数组。我如何格式化我的源数据,或者是否有人有关于创建.NET Web服务或从CSV或数据库生成JSON的其他方法的教程的建议/链接?下面是一个示例数组。

示例:

{
section1: [
{
"id":1,
"title":mytitle1
}
],
{
section2: [
{
"id":2,
"title":mytitle2
}
], etc.....

2 个答案:

答案 0 :(得分:1)

我首先将我的csv文件转换为对象,然后使用newtonsoft的json类将对象解析为JSON

Check this out to learn how to transform CSV to object

Go here to get newtonsoft's json.net tools (can be done using nuget)

答案 1 :(得分:1)

function GetImageToJson:string;     VAR       Q,Q1:TSQLQuery;       content,Liststr:String;       NextRecord:整数;     开始       内容:=' [&#39 ;;       Liststr:='&#39 ;;       问:= TSQLQuery.Create(nil);       Q.Database:= dmDatabase.IBConnection;       Q.SQL.Text:=         ' SELECT ID,TB,NAME FROM V_IMAGES'       Q.Open;       Q.First;       NextRecord:= 0;       如果不是Q.Fields [0] .IsNull然后开始         而不是Q.eof开始            if(NextRecord = 1)然后                Liststr:= Liststr +',&#39 ;;            Liststr:= Liststr +' {" ID" :"' + Q.Fields [0] + .AsString'"&#39 +                                  '" TB" :"' + Q.Fields [1] .AsString +'"&#39 +                                  '" NAME" :"' + Q.Fields [2] .AsString +                            '"}&#39 ;;            NextRecord:= 1;            Q.Next;         端;

  end;
  Q.Free;

  Q := TSQLQuery.Create(nil);
  Q.Database := dmDatabase.IBConnection;
  Q.SQL.Text :=
    'SELECT * FROM sETUP';
  Q.Open;
  Q.First;

  if not Q.Fields[0].IsNull then begin
    while not Q.eof do begin
       if (NextRecord =1) then
           Liststr :=Liststr +',';

       Liststr := Liststr + '{"'+Q.Fields[0].DisplayName+'" : "'        +Q.Fields[0].AsString+'",'+
                         '"'+Q.Fields[1].DisplayName+'" : "'  +Q.Fields[1].AsString+'",'+
                         '"'+Q.Fields[2].DisplayName+'" : "'  +Q.Fields[2].AsString+'",'+
                         '"'+Q.Fields[3].DisplayName+'" : "'  +Q.Fields[3].AsString+'",'+
                         '"'+Q.Fields[4].DisplayName+'" : "'  +Q.Fields[4].AsString+'",'+
                         '"'+Q.Fields[5].DisplayName+'" : "'  +Q.Fields[5].AsString+'",'+
                         '"'+Q.Fields[6].DisplayName+'" : "'  +Q.Fields[6].AsString+'",'+
                         '"'+Q.Fields[7].DisplayName+'" : "'  +Q.Fields[7].AsString+'",'+
                         '"TB":"setup"'+
                   '}';

       NextRecord :=1;
       Q.Next;
    end;

  end;
  Q.Free;


  content := content +Liststr+ ']';
  result  := content;

end;