├── .gitignore
├── Download
├── Essential
│ ├── NDP452-KB2901907-x86-x64-AllOS-ENU.exe
│ └── vstor_redist.exe
├── ExportJson_1_1_0_28.zip
├── ExportJson_1_1_0_29.zip
├── ExportJson_1_1_0_30.zip
├── ExportJson_1_1_0_31.zip
├── ExportJson_1_1_0_32.zip
├── ExportJson_1_1_0_33.zip
└── Run.bat
├── ExportJson-2015.sln
├── ExportJson-2017.sln
├── ExportJson.sln
├── ExportJson.v12.suo
├── ExportJson
├── ExportJson.Designer.cs
├── ExportJson.cs
├── ExportJson.resx
├── ExportJsonPlugin.csproj
├── ExportJsonPlugin.csproj.user
├── ExportJson_TemporaryKey.pfx
├── Properties
│ ├── AssemblyInfo.cs
│ ├── Resources.Designer.cs
│ ├── Resources.resx
│ ├── Settings.Designer.cs
│ └── Settings.settings
├── Settings.cs
├── ThisAddIn.Designer.cs
├── ThisAddIn.Designer.xml
├── ThisAddIn.cs
├── UnityCS.cs
├── app.config
├── fastJSON.cs
├── lib
│ └── dotNetFx45_Full_setup.exe
└── res
│ ├── ConfigLoadTemplate.cs
│ ├── ConfigTemplate.cs
│ ├── josn_icon.ico
│ └── josn_icon.png
└── README.md
/.gitignore:
--------------------------------------------------------------------------------
1 | ## Ignore Visual Studio temporary files, build results, and
2 | ## files generated by popular Visual Studio add-ons.
3 |
4 | # User-specific files
5 | *.suo
6 | *.user
7 | *.userosscache
8 | *.sln.docstates
9 |
10 | # User-specific files (MonoDevelop/Xamarin Studio)
11 | *.userprefs
12 |
13 | # Build results
14 | [Dd]ebug/
15 | [Dd]ebugPublic/
16 | [Rr]elease/
17 | [Rr]eleases/
18 | x64/
19 | x86/
20 | build/
21 | bld/
22 | [Bb]in/
23 | [Oo]bj/
24 |
25 | # Visual Studio 2015 cache/options directory
26 | .vs/
27 |
28 | # MSTest test Results
29 | [Tt]est[Rr]esult*/
30 | [Bb]uild[Ll]og.*
31 |
32 | # NUNIT
33 | *.VisualState.xml
34 | TestResult.xml
35 |
36 | # Build Results of an ATL Project
37 | [Dd]ebugPS/
38 | [Rr]eleasePS/
39 | dlldata.c
40 |
41 | # DNX
42 | project.lock.json
43 | artifacts/
44 |
45 | *_i.c
46 | *_p.c
47 | *_i.h
48 | *.ilk
49 | *.meta
50 | *.obj
51 | *.pch
52 | *.pdb
53 | *.pgc
54 | *.pgd
55 | *.rsp
56 | *.sbr
57 | *.tlb
58 | *.tli
59 | *.tlh
60 | *.tmp
61 | *.tmp_proj
62 | *.log
63 | *.vspscc
64 | *.vssscc
65 | .builds
66 | *.pidb
67 | *.svclog
68 | *.scc
69 |
70 | # Chutzpah Test files
71 | _Chutzpah*
72 |
73 | # Visual C++ cache files
74 | ipch/
75 | *.aps
76 | *.ncb
77 | *.opensdf
78 | *.sdf
79 | *.cachefile
80 |
81 | # Visual Studio profiler
82 | *.psess
83 | *.vsp
84 | *.vspx
85 |
86 | # TFS 2012 Local Workspace
87 | $tf/
88 |
89 | # Guidance Automation Toolkit
90 | *.gpState
91 |
92 | # ReSharper is a .NET coding add-in
93 | _ReSharper*/
94 | *.[Rr]e[Ss]harper
95 | *.DotSettings.user
96 |
97 | # JustCode is a .NET coding add-in
98 | .JustCode
99 |
100 | # TeamCity is a build add-in
101 | _TeamCity*
102 |
103 | # DotCover is a Code Coverage Tool
104 | *.dotCover
105 |
106 | # NCrunch
107 | _NCrunch_*
108 | .*crunch*.local.xml
109 |
110 | # MightyMoose
111 | *.mm.*
112 | AutoTest.Net/
113 |
114 | # Web workbench (sass)
115 | .sass-cache/
116 |
117 | # Installshield output folder
118 | [Ee]xpress/
119 |
120 | # DocProject is a documentation generator add-in
121 | DocProject/buildhelp/
122 | DocProject/Help/*.HxT
123 | DocProject/Help/*.HxC
124 | DocProject/Help/*.hhc
125 | DocProject/Help/*.hhk
126 | DocProject/Help/*.hhp
127 | DocProject/Help/Html2
128 | DocProject/Help/html
129 |
130 | # Click-Once directory
131 | publish/
132 |
133 | # Publish Web Output
134 | *.[Pp]ublish.xml
135 | *.azurePubxml
136 | ## TODO: Comment the next line if you want to checkin your
137 | ## web deploy settings but do note that will include unencrypted
138 | ## passwords
139 | #*.pubxml
140 |
141 | *.publishproj
142 |
143 | # NuGet Packages
144 | *.nupkg
145 | # The packages folder can be ignored because of Package Restore
146 | **/packages/*
147 | # except build/, which is used as an MSBuild target.
148 | !**/packages/build/
149 | # Uncomment if necessary however generally it will be regenerated when needed
150 | #!**/packages/repositories.config
151 |
152 | # Windows Azure Build Output
153 | csx/
154 | *.build.csdef
155 |
156 | # Windows Store app package directory
157 | AppPackages/
158 |
159 | # Visual Studio cache files
160 | # files ending in .cache can be ignored
161 | *.[Cc]ache
162 | # but keep track of directories ending in .cache
163 | !*.[Cc]ache/
164 |
165 | # Others
166 | ClientBin/
167 | [Ss]tyle[Cc]op.*
168 | ~$*
169 | *~
170 | *.dbmdl
171 | *.dbproj.schemaview
172 | *.pfx
173 | *.publishsettings
174 | node_modules/
175 | orleans.codegen.cs
176 |
177 | # RIA/Silverlight projects
178 | Generated_Code/
179 |
180 | # Backup & report files from converting an old project file
181 | # to a newer Visual Studio version. Backup files are not needed,
182 | # because we have git ;-)
183 | _UpgradeReport_Files/
184 | Backup*/
185 | UpgradeLog*.XML
186 | UpgradeLog*.htm
187 |
188 | # SQL Server files
189 | *.mdf
190 | *.ldf
191 |
192 | # Business Intelligence projects
193 | *.rdl.data
194 | *.bim.layout
195 | *.bim_*.settings
196 |
197 | # Microsoft Fakes
198 | FakesAssemblies/
199 |
200 | # Node.js Tools for Visual Studio
201 | .ntvs_analysis.dat
202 |
203 | # Visual Studio 6 build log
204 | *.plg
205 |
206 | # Visual Studio 6 workspace options file
207 | *.opt
208 |
209 | # LightSwitch generated files
210 | GeneratedArtifacts/
211 | _Pvt_Extensions/
212 | ModelManifest.xml
213 | ExportJson/bin/*
214 | ExportJson/obj*
215 | ExportJson/bin/Debug/ExportJson.dll
216 | ExportJson/obj/Debug/DesignTimeResolveAssemblyReferencesInput.cache
217 | ExportJson/obj/Debug/ExportJson.dll
218 |
--------------------------------------------------------------------------------
/Download/Essential/NDP452-KB2901907-x86-x64-AllOS-ENU.exe:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/wanggan768q/ExportJson-for-Excel-2014/b81af59ab1ec2517aef41c4afacb4019d5c55729/Download/Essential/NDP452-KB2901907-x86-x64-AllOS-ENU.exe
--------------------------------------------------------------------------------
/Download/Essential/vstor_redist.exe:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/wanggan768q/ExportJson-for-Excel-2014/b81af59ab1ec2517aef41c4afacb4019d5c55729/Download/Essential/vstor_redist.exe
--------------------------------------------------------------------------------
/Download/ExportJson_1_1_0_28.zip:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/wanggan768q/ExportJson-for-Excel-2014/b81af59ab1ec2517aef41c4afacb4019d5c55729/Download/ExportJson_1_1_0_28.zip
--------------------------------------------------------------------------------
/Download/ExportJson_1_1_0_29.zip:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/wanggan768q/ExportJson-for-Excel-2014/b81af59ab1ec2517aef41c4afacb4019d5c55729/Download/ExportJson_1_1_0_29.zip
--------------------------------------------------------------------------------
/Download/ExportJson_1_1_0_30.zip:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/wanggan768q/ExportJson-for-Excel-2014/b81af59ab1ec2517aef41c4afacb4019d5c55729/Download/ExportJson_1_1_0_30.zip
--------------------------------------------------------------------------------
/Download/ExportJson_1_1_0_31.zip:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/wanggan768q/ExportJson-for-Excel-2014/b81af59ab1ec2517aef41c4afacb4019d5c55729/Download/ExportJson_1_1_0_31.zip
--------------------------------------------------------------------------------
/Download/ExportJson_1_1_0_32.zip:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/wanggan768q/ExportJson-for-Excel-2014/b81af59ab1ec2517aef41c4afacb4019d5c55729/Download/ExportJson_1_1_0_32.zip
--------------------------------------------------------------------------------
/Download/ExportJson_1_1_0_33.zip:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/wanggan768q/ExportJson-for-Excel-2014/b81af59ab1ec2517aef41c4afacb4019d5c55729/Download/ExportJson_1_1_0_33.zip
--------------------------------------------------------------------------------
/Download/Run.bat:
--------------------------------------------------------------------------------
1 | @echo off
2 | call .\\Essential\\vstor_redist.exe
3 | call setup.exe
--------------------------------------------------------------------------------
/ExportJson-2015.sln:
--------------------------------------------------------------------------------
1 |
2 | Microsoft Visual Studio Solution File, Format Version 12.00
3 | # Visual Studio 14
4 | VisualStudioVersion = 14.0.24720.0
5 | MinimumVisualStudioVersion = 10.0.40219.1
6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ExportJsonPlugin", "ExportJson\ExportJsonPlugin.csproj", "{1FD54CD9-CF79-438A-BA29-29F49C6EFAD1}"
7 | EndProject
8 | Global
9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution
10 | Debug|Any CPU = Debug|Any CPU
11 | Release|Any CPU = Release|Any CPU
12 | EndGlobalSection
13 | GlobalSection(ProjectConfigurationPlatforms) = postSolution
14 | {1FD54CD9-CF79-438A-BA29-29F49C6EFAD1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
15 | {1FD54CD9-CF79-438A-BA29-29F49C6EFAD1}.Debug|Any CPU.Build.0 = Debug|Any CPU
16 | {1FD54CD9-CF79-438A-BA29-29F49C6EFAD1}.Release|Any CPU.ActiveCfg = Release|Any CPU
17 | {1FD54CD9-CF79-438A-BA29-29F49C6EFAD1}.Release|Any CPU.Build.0 = Release|Any CPU
18 | EndGlobalSection
19 | GlobalSection(SolutionProperties) = preSolution
20 | HideSolutionNode = FALSE
21 | EndGlobalSection
22 | EndGlobal
23 |
--------------------------------------------------------------------------------
/ExportJson-2017.sln:
--------------------------------------------------------------------------------
1 |
2 | Microsoft Visual Studio Solution File, Format Version 12.00
3 | # Visual Studio 15
4 | VisualStudioVersion = 15.0.26403.7
5 | MinimumVisualStudioVersion = 10.0.40219.1
6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ExportJsonPlugin", "ExportJson\ExportJsonPlugin.csproj", "{1FD54CD9-CF79-438A-BA29-29F49C6EFAD1}"
7 | EndProject
8 | Global
9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution
10 | Debug|Any CPU = Debug|Any CPU
11 | Release|Any CPU = Release|Any CPU
12 | EndGlobalSection
13 | GlobalSection(ProjectConfigurationPlatforms) = postSolution
14 | {1FD54CD9-CF79-438A-BA29-29F49C6EFAD1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
15 | {1FD54CD9-CF79-438A-BA29-29F49C6EFAD1}.Debug|Any CPU.Build.0 = Debug|Any CPU
16 | {1FD54CD9-CF79-438A-BA29-29F49C6EFAD1}.Release|Any CPU.ActiveCfg = Release|Any CPU
17 | {1FD54CD9-CF79-438A-BA29-29F49C6EFAD1}.Release|Any CPU.Build.0 = Release|Any CPU
18 | EndGlobalSection
19 | GlobalSection(SolutionProperties) = preSolution
20 | HideSolutionNode = FALSE
21 | EndGlobalSection
22 | EndGlobal
23 |
--------------------------------------------------------------------------------
/ExportJson.sln:
--------------------------------------------------------------------------------
1 |
2 | Microsoft Visual Studio Solution File, Format Version 12.00
3 | # Visual Studio 2013
4 | VisualStudioVersion = 12.0.31101.0
5 | MinimumVisualStudioVersion = 10.0.40219.1
6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ExportJson", "ExportJson\ExportJson.csproj", "{C81577D8-84AD-40C1-9316-257B0CCCFB22}"
7 | EndProject
8 | Global
9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution
10 | Debug|Any CPU = Debug|Any CPU
11 | Release|Any CPU = Release|Any CPU
12 | EndGlobalSection
13 | GlobalSection(ProjectConfigurationPlatforms) = postSolution
14 | {C81577D8-84AD-40C1-9316-257B0CCCFB22}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
15 | {C81577D8-84AD-40C1-9316-257B0CCCFB22}.Debug|Any CPU.Build.0 = Debug|Any CPU
16 | {C81577D8-84AD-40C1-9316-257B0CCCFB22}.Release|Any CPU.ActiveCfg = Release|Any CPU
17 | {C81577D8-84AD-40C1-9316-257B0CCCFB22}.Release|Any CPU.Build.0 = Release|Any CPU
18 | EndGlobalSection
19 | GlobalSection(SolutionProperties) = preSolution
20 | HideSolutionNode = FALSE
21 | EndGlobalSection
22 | EndGlobal
23 |
--------------------------------------------------------------------------------
/ExportJson.v12.suo:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/wanggan768q/ExportJson-for-Excel-2014/b81af59ab1ec2517aef41c4afacb4019d5c55729/ExportJson.v12.suo
--------------------------------------------------------------------------------
/ExportJson/ExportJson.Designer.cs:
--------------------------------------------------------------------------------
1 | namespace ExportJsonPlugin
2 | {
3 | partial class ExportJson : Microsoft.Office.Tools.Ribbon.RibbonBase
4 | {
5 | ///
6 | /// 必需的设计器变量。
7 | ///
8 | private System.ComponentModel.IContainer components = null;
9 |
10 | public ExportJson()
11 | : base(Globals.Factory.GetRibbonFactory())
12 | {
13 | InitializeComponent();
14 | }
15 |
16 | ///
17 | /// 清理所有正在使用的资源。
18 | ///
19 | /// 如果应释放托管资源,为 true;否则为 false。
20 | protected override void Dispose(bool disposing)
21 | {
22 | if (disposing && (components != null))
23 | {
24 | components.Dispose();
25 | }
26 | base.Dispose(disposing);
27 | }
28 |
29 | #region 组件设计器生成的代码
30 |
31 | ///
32 | /// 设计器支持所需的方法 - 不要修改
33 | /// 使用代码编辑器修改此方法的内容。
34 | ///
35 | private void InitializeComponent()
36 | {
37 | this.tab1 = this.Factory.CreateRibbonTab();
38 | this.JsonGroup = this.Factory.CreateRibbonGroup();
39 | this.typeExportJson = this.Factory.CreateRibbonButton();
40 | this.normalExportJson = this.Factory.CreateRibbonButton();
41 | this.tab1.SuspendLayout();
42 | this.JsonGroup.SuspendLayout();
43 | this.SuspendLayout();
44 | //
45 | // tab1
46 | //
47 | this.tab1.ControlId.ControlIdType = Microsoft.Office.Tools.Ribbon.RibbonControlIdType.Office;
48 | this.tab1.Groups.Add(this.JsonGroup);
49 | this.tab1.Label = "TabAddIns";
50 | this.tab1.Name = "tab1";
51 | //
52 | // JsonGroup
53 | //
54 | this.JsonGroup.Items.Add(this.normalExportJson);
55 | this.JsonGroup.Items.Add(this.typeExportJson);
56 | this.JsonGroup.Name = "JsonGroup";
57 | //
58 | // typeExportJson
59 | //
60 | this.typeExportJson.Label = "类型模式导出JSON文件";
61 | this.typeExportJson.Name = "typeExportJson";
62 | this.typeExportJson.Click += new Microsoft.Office.Tools.Ribbon.RibbonControlEventHandler(this.ExportJsonOfType);
63 | //
64 | // normalExportJson
65 | //
66 | this.normalExportJson.Label = "导出JSON文件";
67 | this.normalExportJson.Name = "normalExportJson";
68 | this.normalExportJson.Click += new Microsoft.Office.Tools.Ribbon.RibbonControlEventHandler(this.ExportJsonOfNormal);
69 | //
70 | // ExportJson
71 | //
72 | this.Name = "ExportJson";
73 | this.RibbonType = "Microsoft.Excel.Workbook";
74 | this.Tabs.Add(this.tab1);
75 | this.Load += new Microsoft.Office.Tools.Ribbon.RibbonUIEventHandler(this.ExportJson_Load);
76 | this.tab1.ResumeLayout(false);
77 | this.tab1.PerformLayout();
78 | this.JsonGroup.ResumeLayout(false);
79 | this.JsonGroup.PerformLayout();
80 | this.ResumeLayout(false);
81 |
82 | }
83 |
84 | #endregion
85 |
86 | internal Microsoft.Office.Tools.Ribbon.RibbonTab tab1;
87 | internal Microsoft.Office.Tools.Ribbon.RibbonGroup JsonGroup;
88 | internal Microsoft.Office.Tools.Ribbon.RibbonButton typeExportJson;
89 | internal Microsoft.Office.Tools.Ribbon.RibbonButton normalExportJson;
90 | }
91 |
92 | partial class ThisRibbonCollection
93 | {
94 | internal ExportJson ExportJson
95 | {
96 | get { return this.GetRibbon(); }
97 | }
98 | }
99 | }
100 |
--------------------------------------------------------------------------------
/ExportJson/ExportJson.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.Office.Tools.Ribbon;
2 | using System;
3 | using System.Collections.Generic;
4 | using System.IO;
5 | using System.Text;
6 | using System.Text.RegularExpressions;
7 | using System.Windows.Forms;
8 | using Excel = Microsoft.Office.Interop.Excel;
9 | using fastJSON;
10 | using ExportJson.Properties;
11 | using System.Linq;
12 |
13 | namespace ExportJsonPlugin
14 | {
15 | public partial class ExportJson
16 | {
17 | private string WorkbookFullName
18 | {
19 | get
20 | {
21 | return Globals.ThisAddIn.Application.ActiveWorkbook.FullName;
22 | }
23 | }
24 | private void ExportJson_Load(object sender, RibbonUIEventArgs e)
25 | {
26 | }
27 |
28 | private void Save(string json)
29 | {
30 | try
31 | {
32 | JSON.Instance.Parse(json);
33 | }
34 | catch (System.Exception _ex)
35 | {
36 | MessageBox.Show("数据异常,请检查");
37 | return;
38 | }
39 | // SaveFileDialog saveFileDialog = new SaveFileDialog();
40 | // saveFileDialog.Filter = "json文件(*.json)|";
41 | // string fileName = Path.GetFileNameWithoutExtension(Globals.ThisAddIn.Application.ActiveWorkbook.FullName);
42 | // string[] titles = fileName.Split('_');
43 | // string name = titles[0];
44 | // saveFileDialog.InitialDirectory = Path.GetDirectoryName(fileName);
45 | // saveFileDialog.FileName = name;
46 | // saveFileDialog.ShowDialog();
47 |
48 | string fileName = Path.GetFileNameWithoutExtension(WorkbookFullName);
49 | string[] titles = fileName.Split('_');
50 | string name = titles[0];
51 |
52 | string path = Path.GetDirectoryName(WorkbookFullName) + Path.DirectorySeparatorChar + "Out" + Path.DirectorySeparatorChar + "Json";
53 | if (!Directory.Exists(path))
54 | {
55 | Directory.CreateDirectory(path);
56 | }
57 |
58 | string jsonFileName = "";
59 | if (!fileName.EndsWith(".json"))
60 | {
61 | //jsonFileName = saveFileDialog.FileName + ".json";
62 | jsonFileName = path + Path.DirectorySeparatorChar + name + ".json";
63 | }
64 |
65 | if (jsonFileName.Contains(":"))
66 | {
67 | FileStream fs = new FileStream(jsonFileName, FileMode.CreateNew | FileMode.OpenOrCreate);
68 | StreamWriter sw = new StreamWriter(fs);
69 | sw.Write(json);
70 | sw.Close();
71 | MessageBox.Show("导出完成");
72 | }
73 | }
74 |
75 | ///
76 | /// 把所有数据导出
77 | /// 1.字段
78 | /// 2.数据
79 | ///
80 | ///
81 | ///
82 | private void ExportJsonOfNormal(object sender, RibbonControlEventArgs e)
83 | {
84 | Excel.Worksheet activeWorksheet = Globals.ThisAddIn.Application.ActiveSheet;
85 | if(activeWorksheet == null)
86 | {
87 | MessageBox.Show("请启动编辑模式");
88 | return;
89 | }
90 | List _Keys = new List();
91 |
92 | List keyRang = GetLine(activeWorksheet, 1);
93 | if (keyRang.Count == 0)
94 | {
95 | return;
96 | }
97 | foreach (string cell in keyRang)
98 | {
99 | _Keys.Add(cell);
100 | }
101 | if (_Keys.Count == 0)
102 | {
103 | return;
104 | }
105 |
106 | StringBuilder stringBuilder = new StringBuilder();
107 | stringBuilder.Append("[");
108 |
109 | int keyCount = keyRang.Count;
110 | int index = 1;
111 | while (true)
112 | {
113 | List dataRang = GetLine(activeWorksheet, ++index);
114 | if (dataRang.Count == 0)
115 | {
116 | break;
117 | }
118 | stringBuilder.Append("{");
119 |
120 | for (int i = 0; i < _Keys.Count; ++i)
121 | {
122 | stringBuilder.Append("\"" + _Keys[i] + "\":");
123 | if (i < dataRang.Count)
124 | {
125 | StringBuilder v1 = new StringBuilder(dataRang[i]);
126 | //string v = dataRang[i].Text;
127 | string v = v1.ToString().TrimEnd();
128 | bool isInteger = Regex.IsMatch(v, @"^[-]?[1-9]{1}\d*$|^[0]{1}$");
129 | bool isDecimal = Regex.IsMatch(v, @"^(-?\d+)(\.\d+)?$");
130 | if (isInteger)
131 | {
132 | stringBuilder.Append(Convert.ToInt64(v));
133 | }
134 | else if (isDecimal)
135 | {
136 | stringBuilder.Append(Convert.ToDouble(v));
137 | }
138 | else
139 | {
140 | //v = v.Replace('\r', ' ');
141 | v = v.Replace('\n', ' ');
142 | stringBuilder.Append("\"" + v + "\"");
143 | }
144 | }
145 | else
146 | {
147 | stringBuilder.Append("");
148 | }
149 | if (i != _Keys.Count - 1)
150 | {
151 | stringBuilder.Append(",");
152 | }
153 | }
154 | stringBuilder.Append("},");
155 | }
156 | stringBuilder.Remove(stringBuilder.Length - 1, 1);
157 | stringBuilder.Append("]");
158 | string json = stringBuilder.ToString();
159 | /*
160 | byte[] unicodeBuf = Encoding.Unicode.GetBytes(json);
161 | byte[] utfBuf = Encoding.Convert(Encoding.Unicode, Encoding.UTF8, unicodeBuf);
162 | json = Encoding.UTF8.GetString(utfBuf);
163 | * */
164 | //验证JSON
165 | /*
166 | string utfJson = GB2312ToUTF8(json);
167 |
168 | JsonData dataSrc = JsonMapper.ToObject(utfJson);
169 | int a = 0;
170 | */
171 |
172 | this.Save(json);
173 | }
174 |
175 |
176 | //字段类型
177 | List typeRang = new List();
178 | //字段名称
179 | List keyRang = new List();
180 |
181 | ///
182 | /// 根据类型导出数据
183 | /// 1.描述
184 | /// 2.类型 I->int F->float S->String B->bool
185 | /// 3.字段
186 | /// 4.数据 一级分隔符| 二级分隔符 _
187 | ///
188 | ///
189 | ///
190 | private void ExportJsonOfType(object sender, RibbonControlEventArgs e)
191 | {
192 | typeRang.Clear();
193 | keyRang.Clear();
194 |
195 | Excel.Worksheet activeWorksheet = Globals.ThisAddIn.Application.ActiveSheet;
196 | string[] fileName = activeWorksheet.Application.Caption.Split('.');
197 |
198 | List Keys = new List();
199 |
200 | List Des = new List();
201 | Des = GetLine(activeWorksheet, 1);
202 |
203 | keyRang = GetLine(activeWorksheet, 3);
204 |
205 | typeRang = GetLine(activeWorksheet, 2);
206 |
207 |
208 |
209 | if (typeRang.Count != keyRang.Count || typeRang.Count == 0 || keyRang.Count == 0)
210 | {
211 | MessageBox.Show("字段和类型个数不匹配");
212 | return;
213 | }
214 | Dictionary _FieldsDic = new Dictionary();
215 | for (int i = 0; i < keyRang.Count; ++i)
216 | {
217 | string cell = keyRang[i];
218 | _FieldsDic.Add(cell, typeRang[i]);
219 | Keys.Add(cell);
220 | }
221 |
222 | if (_FieldsDic.Count == 0)
223 | {
224 | return;
225 | }
226 |
227 | StringBuilder stringBuilder = new StringBuilder();
228 | stringBuilder.Append("[");
229 | int index = 3;
230 | while (true)
231 | {
232 | List dataRang = GetLine(activeWorksheet, ++index,false);
233 | if (dataRang.Count == 0)
234 | {
235 | break;
236 | }
237 |
238 | stringBuilder.Append("{");
239 |
240 | for (int i = 0; i < Keys.Count; ++i)
241 | {
242 | stringBuilder.Append("\"" + ((string)keyRang[i]).Trim() + "\":");
243 | string fieldType = ((string)typeRang[i]).Trim();
244 | if (i < dataRang.Count)
245 | {
246 | StringBuilder v1 = new StringBuilder(dataRang[i]);
247 | //string v = dataRang[i].Text;
248 | string v = v1.ToString().TrimEnd();
249 |
250 | switch (fieldType)
251 | {
252 | case "I":
253 | {
254 | stringBuilder.Append(Convert.ToInt64(v));
255 | }
256 | break;
257 | case "F":
258 | {
259 | stringBuilder.AppendFormat("{0:F}",Convert.ToDouble(v));
260 | }
261 | break;
262 | case "S":
263 | {
264 | v = v.Replace('\r', ' ');
265 | v = v.Replace('\n', ' ');
266 | stringBuilder.Append("\"" + v + "\"");
267 | }
268 | break;
269 | case "B":
270 | {
271 | v = v.Trim();
272 | v = v.ToLower();
273 | if (v.Equals("0") || v.Equals(bool.FalseString.ToLower()))
274 | {
275 | stringBuilder.Append(bool.FalseString.ToLower());
276 | }
277 | else if (v.Equals("1") || v.Equals(bool.TrueString.ToLower()))
278 | {
279 | stringBuilder.Append(bool.TrueString.ToLower());
280 | }
281 | else
282 | {
283 | MessageBox.Show("错误的类型: [ " + fieldType + " ]");
284 | }
285 | }
286 | break;
287 | default:
288 | {
289 | MessageBox.Show("错误的类型: [ " + fieldType + " ]");
290 | }
291 | break;
292 | }
293 | }
294 | else
295 | {
296 | stringBuilder.Append("");
297 | }
298 | if (i != Keys.Count - 1)
299 | {
300 | stringBuilder.Append(",");
301 | }
302 | }
303 | stringBuilder.Append("},");
304 | }
305 | stringBuilder.Remove(stringBuilder.Length - 1, 1);
306 | stringBuilder.Append("]");
307 | string json = stringBuilder.ToString();
308 | this.Save(json);
309 |
310 | UnityCS cs = new UnityCS();
311 | cs.Export(fileName[0], typeRang, keyRang,Des);
312 | }
313 |
314 |
315 |
316 |
317 | ///
318 | ///
319 | ///
320 | ///
321 | ///
322 | /// 是否判null
323 | ///
324 | private List GetLine(Excel.Worksheet sheet, int lineNum,bool assert = true)
325 | {
326 | char a = 'A';
327 | char z = 'Z';
328 |
329 | int col = 1000;
330 |
331 | string colStr = "";
332 | List _Cells = new List();
333 |
334 | for (int c = 0; c < col; ++c)
335 | {
336 | string rStr = string.Format("{0}{1}", colStr + a, lineNum);
337 | a++;
338 | if (a > z)
339 | {
340 | a = 'A';
341 | colStr += a;
342 | }
343 | Excel.Range line = sheet.get_Range(rStr);
344 | string tempV = line.Text;
345 | if (string.IsNullOrEmpty(tempV))
346 | {
347 | if(assert || c == typeRang.Count)
348 | {
349 | break;
350 | }
351 | if(c < typeRang.Count)
352 | {
353 | string type = ((string)typeRang[c]).Trim();
354 | switch (type)
355 | {
356 | case "I":
357 | case "F":
358 | case "B":
359 | {
360 | tempV = "0";
361 | }
362 | break;
363 | case "S":
364 | {
365 | tempV = "";
366 | }
367 | break;
368 | default:
369 | {
370 | MessageBox.Show("错误的类型: [ " + type + " ]");
371 | }
372 | break;
373 | }
374 | }
375 | }
376 | _Cells.Add(tempV);
377 | }
378 |
379 | int index = 0;
380 | List tempDataRang = _Cells.FindAll((string s) =>
381 | {
382 | if (string.IsNullOrEmpty(s) || s.Equals("0"))
383 | {
384 | if (++index == _Cells.Count)
385 | {
386 | _Cells.Clear();
387 | }
388 | return true;
389 | }
390 |
391 | return false;
392 | });
393 | return _Cells;
394 | }
395 | }
396 | }
--------------------------------------------------------------------------------
/ExportJson/ExportJson.resx:
--------------------------------------------------------------------------------
1 |
2 |
3 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 |
73 |
74 |
75 |
76 |
77 |
78 |
79 |
80 |
81 |
82 |
83 |
84 |
85 |
86 |
87 |
88 |
89 |
90 |
91 |
92 |
93 |
94 |
95 |
96 |
97 |
98 |
99 |
100 |
101 |
102 |
103 |
104 |
105 |
106 |
107 |
108 |
109 | text/microsoft-resx
110 |
111 |
112 | 2.0
113 |
114 |
115 | System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
116 |
117 |
118 | System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
119 |
120 |
--------------------------------------------------------------------------------
/ExportJson/ExportJsonPlugin.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
21 |
22 | {BAA0C2D2-18E2-41B9-852F-F413020CAA33};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}
23 | Debug
24 | AnyCPU
25 | {1FD54CD9-CF79-438A-BA29-29F49C6EFAD1}
26 | Library
27 | false
28 | ExportJson
29 | ExportJson
30 | v4.5
31 | VSTO40
32 | True
33 |
34 | true
35 | F:\GitHub\ExportJson-for-Excel-2014\Download\
36 | https://github.com/wanggan768q/ExportJson-for-Excel-2014/blob/master/Download/
37 | zh-chs
38 | 1.1.0.32
39 | true
40 | true
41 | 0
42 | days
43 | ExportJson
44 | 郭晓波
45 |
46 | ExportJson
47 |
48 | 3
49 |
50 |
51 |
52 | False
53 | Microsoft .NET Framework 4 %28x86 和 x64%29
54 | true
55 |
56 |
57 | False
58 | Microsoft .NET Framework 4.5 %28x86 和 x64%29
59 | true
60 |
61 |
62 | False
63 | .NET Framework 3.5 SP1 Client Profile
64 | false
65 |
66 |
67 | False
68 | .NET Framework 3.5 SP1
69 | false
70 |
71 |
72 | False
73 | Microsoft Visual Studio 2010 Tools for Office Runtime %28x86 和 x64%29
74 | true
75 |
76 |
77 | False
78 | Windows Installer 4.5
79 | true
80 |
81 |
82 |
83 |
87 | Excel
88 |
89 |
105 |
106 | true
107 | full
108 | false
109 | bin\Debug\
110 | false
111 | $(DefineConstants);DEBUG;TRACE
112 | 4
113 | false
114 |
115 |
131 |
132 | pdbonly
133 | true
134 | bin\Release\
135 | false
136 | $(DefineConstants);TRACE
137 | 4
138 | false
139 |
140 |
143 |
144 |
145 |
146 |
147 |
148 |
149 |
150 |
151 |
152 |
153 |
154 |
155 |
156 |
157 |
158 |
159 |
160 |
161 |
162 |
163 |
164 | True
165 |
166 |
167 |
168 |
169 | False
170 | true
171 |
172 |
173 | False
174 | true
175 |
176 |
177 | False
178 |
179 |
180 |
190 |
191 |
192 | Component
193 |
194 |
195 | ExportJson.cs
196 |
197 |
198 |
199 | Code
200 |
201 |
202 |
203 |
204 |
205 | ExportJson.cs
206 |
207 |
208 | PublicResXFileCodeGenerator
209 | Resources.Designer.cs
210 | Designer
211 |
212 |
213 | True
214 | Resources.resx
215 | True
216 |
217 |
218 |
219 |
220 | SettingsSingleFileGenerator
221 | Settings.Designer.cs
222 |
223 |
224 | True
225 | Settings.settings
226 | True
227 |
228 |
229 |
230 | Code
231 |
232 |
233 | ThisAddIn.cs
234 |
235 |
236 | ThisAddIn.Designer.xml
237 |
238 |
239 |
240 |
241 |
242 |
243 |
244 |
245 |
246 |
247 |
248 |
249 |
250 | 10.0
251 | $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)
252 |
253 |
254 | true
255 |
256 |
257 |
258 |
259 |
260 |
261 | 63EA093DAAA4BF3586973B0875A7EE64BC188154
262 |
263 |
264 |
265 |
266 |
267 | true
268 |
269 |
270 | ExportJson_TemporaryKey.pfx
271 |
272 |
273 |
274 |
275 |
276 |
277 | false
278 |
279 |
280 |
281 |
282 |
283 |
284 |
285 |
286 |
287 |
288 |
289 |
290 |
291 |
292 |
293 |
294 |
--------------------------------------------------------------------------------
/ExportJson/ExportJsonPlugin.csproj.user:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | F:\GitHub\ExportJson-for-Excel-2014\Download\
5 | https://github.com/wanggan768q/ExportJson-for-Excel-2014/blob/master/Download/
6 |
7 | ProjectFiles
8 |
9 |
10 | Project
11 | false
12 |
13 |
--------------------------------------------------------------------------------
/ExportJson/ExportJson_TemporaryKey.pfx:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/wanggan768q/ExportJson-for-Excel-2014/b81af59ab1ec2517aef41c4afacb4019d5c55729/ExportJson/ExportJson_TemporaryKey.pfx
--------------------------------------------------------------------------------
/ExportJson/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using System.Reflection;
2 | using System.Runtime.CompilerServices;
3 | using System.Runtime.InteropServices;
4 | using System.Security;
5 |
6 | // 有关程序集的常规信息通过下列特性集
7 | // 控制。更改这些特性值可修改
8 | // 与程序集关联的信息。
9 | [assembly: AssemblyTitle("ExportJson")]
10 | [assembly: AssemblyDescription("")]
11 | [assembly: AssemblyConfiguration("")]
12 | [assembly: AssemblyCompany("")]
13 | [assembly: AssemblyProduct("ExportJson")]
14 | [assembly: AssemblyCopyright("Copyright © 2015")]
15 | [assembly: AssemblyTrademark("")]
16 | [assembly: AssemblyCulture("")]
17 |
18 | // 将 ComVisible 设置为 false 会使此程序集中的类型
19 | // 对 COM 组件不可见。 如果需要从 COM 访问此程序集中的类型,
20 | // 则将该类型的 ComVisible 特性设置为 true。
21 | [assembly: ComVisible(false)]
22 |
23 | // 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
24 | [assembly: Guid("d58d077d-b0ed-4e66-a749-badd3b90db05")]
25 |
26 | // 程序集的版本信息由下面四个值组成:
27 | //
28 | // 主版本
29 | // 次版本
30 | // 生成号
31 | // 修订号
32 | //
33 | // 可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值,
34 | // 方法是按如下所示使用“*”:
35 | // [assembly: AssemblyVersion("1.0.*")]
36 | [assembly: AssemblyVersion("1.0.0.0")]
37 | [assembly: AssemblyFileVersion("1.0.0.0")]
38 |
39 |
--------------------------------------------------------------------------------
/ExportJson/Properties/Resources.Designer.cs:
--------------------------------------------------------------------------------
1 | //------------------------------------------------------------------------------
2 | //
3 | // 此代码由工具生成。
4 | // 运行时版本:4.0.30319.42000
5 | //
6 | // 对此文件的更改可能会导致不正确的行为,并且如果
7 | // 重新生成代码,这些更改将会丢失。
8 | //
9 | //------------------------------------------------------------------------------
10 |
11 | namespace ExportJson.Properties {
12 | using System;
13 |
14 |
15 | ///
16 | /// 一个强类型的资源类,用于查找本地化的字符串等。
17 | ///
18 | // 此类是由 StronglyTypedResourceBuilder
19 | // 类通过类似于 ResGen 或 Visual Studio 的工具自动生成的。
20 | // 若要添加或移除成员,请编辑 .ResX 文件,然后重新运行 ResGen
21 | // (以 /str 作为命令选项),或重新生成 VS 项目。
22 | [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
23 | [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
24 | [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
25 | public class Resources {
26 |
27 | private static global::System.Resources.ResourceManager resourceMan;
28 |
29 | private static global::System.Globalization.CultureInfo resourceCulture;
30 |
31 | [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
32 | internal Resources() {
33 | }
34 |
35 | ///
36 | /// 返回此类使用的缓存的 ResourceManager 实例。
37 | ///
38 | [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
39 | public static global::System.Resources.ResourceManager ResourceManager {
40 | get {
41 | if (object.ReferenceEquals(resourceMan, null)) {
42 | global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("ExportJson.Properties.Resources", typeof(Resources).Assembly);
43 | resourceMan = temp;
44 | }
45 | return resourceMan;
46 | }
47 | }
48 |
49 | ///
50 | /// 使用此强类型资源类,为所有资源查找
51 | /// 重写当前线程的 CurrentUICulture 属性。
52 | ///
53 | [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
54 | public static global::System.Globalization.CultureInfo Culture {
55 | get {
56 | return resourceCulture;
57 | }
58 | set {
59 | resourceCulture = value;
60 | }
61 | }
62 |
63 | ///
64 | /// 查找类似 using UnityEngine;
65 | ///using System.Collections;
66 | ///
67 | ///public class ConfigLoad : MonoBehaviour {
68 | ///
69 | /// private string textContent;
70 | ///
71 | /// public IEnumerator LoadConfig () {
72 | ///
73 | ///$loadConfItem$
74 | ///
75 | /// yield return true;
76 | /// }
77 | ///
78 | /// IEnumerator LoadData (string name) {
79 | ///
80 | /// string path = Ex.Utils.GetStreamingAssetsFilePath(name, "CSV");
81 | ///
82 | /// WWW www = new WWW(path);
83 | /// yield return www;
84 | ///
85 | /// textContent = www.text;
86 | /// yield return true;
87 | /// }
88 | ///}
89 | /// 的本地化字符串。
90 | ///
91 | public static string ConfigLoadTemplate {
92 | get {
93 | return ResourceManager.GetString("ConfigLoadTemplate", resourceCulture);
94 | }
95 | }
96 |
97 | ///
98 | /// 查找类似 using UnityEngine;
99 | ///using System;
100 | ///using System.IO;
101 | ///using System.Collections;
102 | ///using System.Collections.Generic;
103 | ///using HS.IO;
104 | ///using LitJson;
105 | ///
106 | ///
107 | ///public class $Template$Element
108 | ///{
109 | ///$FieldDefine$
110 | /// public bool IsValidate = false;
111 | /// public $Template$Element()
112 | /// {
113 | /// $InitPrimaryField$
114 | /// }
115 | ///};
116 | ///
117 | ///
118 | ///public class $Template$Table
119 | ///{
120 | ///
121 | /// private $Template$Table()
122 | /// {
123 | /// _MapElements = new Dictionary<int, $Template$Element>();
124 | /// _EmptyItem = new $Template$Element();
125 | /// _VecAllElements = new List<$Template$Eleme [字符串的其余部分被截断]"; 的本地化字符串。
126 | ///
127 | public static string ConfigTemplate {
128 | get {
129 | return ResourceManager.GetString("ConfigTemplate", resourceCulture);
130 | }
131 | }
132 |
133 | ///
134 | /// 查找类似于 (Icon) 的 System.Drawing.Icon 类型的本地化资源。
135 | ///
136 | public static System.Drawing.Icon josn_icon {
137 | get {
138 | object obj = ResourceManager.GetObject("josn_icon", resourceCulture);
139 | return ((System.Drawing.Icon)(obj));
140 | }
141 | }
142 | }
143 | }
144 |
--------------------------------------------------------------------------------
/ExportJson/Properties/Resources.resx:
--------------------------------------------------------------------------------
1 |
2 |
3 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 |
73 |
74 |
75 |
76 |
77 |
78 |
79 |
80 |
81 |
82 |
83 |
84 |
85 |
86 |
87 |
88 |
89 |
90 |
91 |
92 |
93 |
94 |
95 |
96 |
97 |
98 |
99 |
100 |
101 |
102 |
103 |
104 |
105 |
106 |
107 |
108 |
109 | text/microsoft-resx
110 |
111 |
112 | 2.0
113 |
114 |
115 | System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
116 |
117 |
118 | System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
119 |
120 |
121 |
122 | ..\res\ConfigLoadTemplate.cs;System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089;utf-8
123 |
124 |
125 | ..\res\ConfigTemplate.cs;System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089;gb2312
126 |
127 |
128 | ..\res\josn_icon.ico;System.Drawing.Icon, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a
129 |
130 |
--------------------------------------------------------------------------------
/ExportJson/Properties/Settings.Designer.cs:
--------------------------------------------------------------------------------
1 | //------------------------------------------------------------------------------
2 | //
3 | // 此代码由工具生成。
4 | // 运行时版本:4.0.30319.42000
5 | //
6 | // 对此文件的更改可能会导致不正确的行为,并且如果
7 | // 重新生成代码,这些更改将会丢失。
8 | //
9 | //------------------------------------------------------------------------------
10 |
11 | namespace ExportJsonPlugin.Properties {
12 |
13 |
14 | [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
15 | [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "14.0.0.0")]
16 | internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase {
17 |
18 | private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
19 |
20 | public static Settings Default {
21 | get {
22 | return defaultInstance;
23 | }
24 | }
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/ExportJson/Properties/Settings.settings:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/ExportJson/Settings.cs:
--------------------------------------------------------------------------------
1 | namespace ExportJsonPlugin.Properties {
2 |
3 |
4 | // 通过此类可以处理设置类的特定事件:
5 | // 在更改某个设置的值之前将引发 SettingChanging 事件。
6 | // 在更改某个设置的值之后将引发 PropertyChanged 事件。
7 | // 在加载设置值之后将引发 SettingsLoaded 事件。
8 | // 在保存设置值之前将引发 SettingsSaving 事件。
9 | internal sealed partial class Settings {
10 |
11 | public Settings() {
12 | // // 若要为保存和更改设置添加事件处理程序,请取消注释下列行:
13 | //
14 | // this.SettingChanging += this.SettingChangingEventHandler;
15 | //
16 | // this.SettingsSaving += this.SettingsSavingEventHandler;
17 | //
18 | }
19 |
20 | private void SettingChangingEventHandler(object sender, System.Configuration.SettingChangingEventArgs e) {
21 | // 在此处添加用于处理 SettingChangingEvent 事件的代码。
22 | }
23 |
24 | private void SettingsSavingEventHandler(object sender, System.ComponentModel.CancelEventArgs e) {
25 | // 在此处添加用于处理 SettingsSaving 事件的代码。
26 | }
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/ExportJson/ThisAddIn.Designer.cs:
--------------------------------------------------------------------------------
1 | //------------------------------------------------------------------------------
2 | //
3 | // 此代码由工具生成。
4 | // 运行时版本:4.0.30319.42000
5 | //
6 | // 对此文件的更改可能会导致不正确的行为,并且如果
7 | // 重新生成代码,这些更改将会丢失。
8 | //
9 | //------------------------------------------------------------------------------
10 |
11 | #pragma warning disable 414
12 | namespace ExportJsonPlugin {
13 |
14 |
15 | ///
16 | [Microsoft.VisualStudio.Tools.Applications.Runtime.StartupObjectAttribute(0)]
17 | [global::System.Security.Permissions.PermissionSetAttribute(global::System.Security.Permissions.SecurityAction.Demand, Name="FullTrust")]
18 | public sealed partial class ThisAddIn : Microsoft.Office.Tools.AddInBase {
19 |
20 | internal Microsoft.Office.Tools.CustomTaskPaneCollection CustomTaskPanes;
21 |
22 | internal Microsoft.Office.Tools.SmartTagCollection VstoSmartTags;
23 |
24 | [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Tools.Office.ProgrammingModel.dll", "14.0.0.0")]
25 | private global::System.Object missing = global::System.Type.Missing;
26 |
27 | [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Tools.Office.ProgrammingModel.dll", "14.0.0.0")]
28 | internal Microsoft.Office.Interop.Excel.Application Application;
29 |
30 | ///
31 | [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
32 | [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Never)]
33 | public ThisAddIn(global::Microsoft.Office.Tools.Excel.ApplicationFactory factory, global::System.IServiceProvider serviceProvider) :
34 | base(factory, serviceProvider, "AddIn", "ThisAddIn") {
35 | Globals.Factory = factory;
36 | }
37 |
38 | ///
39 | [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
40 | [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Tools.Office.ProgrammingModel.dll", "14.0.0.0")]
41 | [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Never)]
42 | protected override void Initialize() {
43 | base.Initialize();
44 | this.Application = this.GetHostItem(typeof(Microsoft.Office.Interop.Excel.Application), "Application");
45 | Globals.ThisAddIn = this;
46 | global::System.Windows.Forms.Application.EnableVisualStyles();
47 | this.InitializeCachedData();
48 | this.InitializeControls();
49 | this.InitializeComponents();
50 | this.InitializeData();
51 | }
52 |
53 | ///
54 | [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
55 | [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Tools.Office.ProgrammingModel.dll", "14.0.0.0")]
56 | [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Never)]
57 | protected override void FinishInitialization() {
58 | this.InternalStartup();
59 | this.OnStartup();
60 | }
61 |
62 | ///
63 | [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
64 | [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Tools.Office.ProgrammingModel.dll", "14.0.0.0")]
65 | [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Never)]
66 | protected override void InitializeDataBindings() {
67 | this.BeginInitialization();
68 | this.BindToData();
69 | this.EndInitialization();
70 | }
71 |
72 | ///
73 | [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
74 | [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Tools.Office.ProgrammingModel.dll", "14.0.0.0")]
75 | [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Never)]
76 | private void InitializeCachedData() {
77 | if ((this.DataHost == null)) {
78 | return;
79 | }
80 | if (this.DataHost.IsCacheInitialized) {
81 | this.DataHost.FillCachedData(this);
82 | }
83 | }
84 |
85 | ///
86 | [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
87 | [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Tools.Office.ProgrammingModel.dll", "14.0.0.0")]
88 | [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Never)]
89 | private void InitializeData() {
90 | }
91 |
92 | ///
93 | [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
94 | [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Tools.Office.ProgrammingModel.dll", "14.0.0.0")]
95 | [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Never)]
96 | private void BindToData() {
97 | }
98 |
99 | ///
100 | [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
101 | [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
102 | private void StartCaching(string MemberName) {
103 | this.DataHost.StartCaching(this, MemberName);
104 | }
105 |
106 | ///
107 | [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
108 | [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
109 | private void StopCaching(string MemberName) {
110 | this.DataHost.StopCaching(this, MemberName);
111 | }
112 |
113 | ///
114 | [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
115 | [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
116 | private bool IsCached(string MemberName) {
117 | return this.DataHost.IsCached(this, MemberName);
118 | }
119 |
120 | ///
121 | [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
122 | [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Tools.Office.ProgrammingModel.dll", "14.0.0.0")]
123 | [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Never)]
124 | private void BeginInitialization() {
125 | this.BeginInit();
126 | this.CustomTaskPanes.BeginInit();
127 | this.VstoSmartTags.BeginInit();
128 | }
129 |
130 | ///
131 | [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
132 | [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Tools.Office.ProgrammingModel.dll", "14.0.0.0")]
133 | [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Never)]
134 | private void EndInitialization() {
135 | this.VstoSmartTags.EndInit();
136 | this.CustomTaskPanes.EndInit();
137 | this.EndInit();
138 | }
139 |
140 | ///
141 | [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
142 | [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Tools.Office.ProgrammingModel.dll", "14.0.0.0")]
143 | [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Never)]
144 | private void InitializeControls() {
145 | this.CustomTaskPanes = Globals.Factory.CreateCustomTaskPaneCollection(null, null, "CustomTaskPanes", "CustomTaskPanes", this);
146 | this.VstoSmartTags = Globals.Factory.CreateSmartTagCollection(null, null, "VstoSmartTags", "VstoSmartTags", this);
147 | }
148 |
149 | ///
150 | [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
151 | [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Tools.Office.ProgrammingModel.dll", "14.0.0.0")]
152 | [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Never)]
153 | private void InitializeComponents() {
154 | }
155 |
156 | ///
157 | [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
158 | [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
159 | private bool NeedsFill(string MemberName) {
160 | return this.DataHost.NeedsFill(this, MemberName);
161 | }
162 |
163 | ///
164 | [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
165 | [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Tools.Office.ProgrammingModel.dll", "14.0.0.0")]
166 | [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Never)]
167 | protected override void OnShutdown() {
168 | this.VstoSmartTags.Dispose();
169 | this.CustomTaskPanes.Dispose();
170 | base.OnShutdown();
171 | }
172 | }
173 |
174 | ///
175 | [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
176 | [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Tools.Office.ProgrammingModel.dll", "14.0.0.0")]
177 | internal sealed partial class Globals {
178 |
179 | ///
180 | private Globals() {
181 | }
182 |
183 | private static ThisAddIn _ThisAddIn;
184 |
185 | private static global::Microsoft.Office.Tools.Excel.ApplicationFactory _factory;
186 |
187 | private static ThisRibbonCollection _ThisRibbonCollection;
188 |
189 | internal static ThisAddIn ThisAddIn {
190 | get {
191 | return _ThisAddIn;
192 | }
193 | set {
194 | if ((_ThisAddIn == null)) {
195 | _ThisAddIn = value;
196 | }
197 | else {
198 | throw new System.NotSupportedException();
199 | }
200 | }
201 | }
202 |
203 | internal static global::Microsoft.Office.Tools.Excel.ApplicationFactory Factory {
204 | get {
205 | return _factory;
206 | }
207 | set {
208 | if ((_factory == null)) {
209 | _factory = value;
210 | }
211 | else {
212 | throw new System.NotSupportedException();
213 | }
214 | }
215 | }
216 |
217 | internal static ThisRibbonCollection Ribbons {
218 | get {
219 | if ((_ThisRibbonCollection == null)) {
220 | _ThisRibbonCollection = new ThisRibbonCollection(_factory.GetRibbonFactory());
221 | }
222 | return _ThisRibbonCollection;
223 | }
224 | }
225 | }
226 |
227 | ///
228 | [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
229 | [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Tools.Office.ProgrammingModel.dll", "14.0.0.0")]
230 | internal sealed partial class ThisRibbonCollection : Microsoft.Office.Tools.Ribbon.RibbonCollectionBase {
231 |
232 | ///
233 | internal ThisRibbonCollection(global::Microsoft.Office.Tools.Ribbon.RibbonFactory factory) :
234 | base(factory) {
235 | }
236 | }
237 | }
238 |
--------------------------------------------------------------------------------
/ExportJson/ThisAddIn.Designer.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/ExportJson/ThisAddIn.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Xml.Linq;
6 | using Excel = Microsoft.Office.Interop.Excel;
7 | using Office = Microsoft.Office.Core;
8 | using Microsoft.Office.Tools.Excel;
9 | using System.Text.RegularExpressions;
10 | using System.IO;
11 | using Microsoft.Office.Tools.Ribbon;
12 |
13 | namespace ExportJsonPlugin
14 | {
15 | public partial class ThisAddIn
16 | {
17 | private void ThisAddIn_Startup(object sender, System.EventArgs e)
18 | {
19 | //this.Application.WorkbookBeforeSave += new Microsoft.Office.Interop.Excel.AppEvents_WorkbookBeforeSaveEventHandler(Application_WorkbookBeforeSave);
20 | }
21 |
22 | private void ThisAddIn_Shutdown(object sender, System.EventArgs e)
23 | {
24 | }
25 |
26 | #region VSTO 生成的代码
27 |
28 | ///
29 | /// 设计器支持所需的方法 - 不要
30 | /// 使用代码编辑器修改此方法的内容。
31 | ///
32 | private void InternalStartup()
33 | {
34 | this.Startup += new System.EventHandler(ThisAddIn_Startup);
35 | this.Shutdown += new System.EventHandler(ThisAddIn_Shutdown);
36 | }
37 | #endregion
38 |
39 | protected override IRibbonExtension[] CreateRibbonObjects()
40 | {
41 | return new IRibbonExtension[] { new ExportJson() };
42 | }
43 | }
44 | }
45 |
--------------------------------------------------------------------------------
/ExportJson/UnityCS.cs:
--------------------------------------------------------------------------------
1 | using ExportJson.Properties;
2 | using System.Collections.Generic;
3 | using System.IO;
4 | using System.Linq;
5 | using System.Text;
6 |
7 | namespace ExportJsonPlugin
8 | {
9 | class UnityCS
10 | {
11 | public const string T1 = "\t";
12 | public const string T2 = "\t\t";
13 | public const string T3 = "\t\t\t";
14 | public const string T4 = "\t\t\t\t";
15 |
16 | private string WorkbookFullName
17 | {
18 | get
19 | {
20 | return Globals.ThisAddIn.Application.ActiveWorkbook.FullName;
21 | }
22 | }
23 |
24 | private string CSPath
25 | {
26 | get
27 | {
28 | return Path.GetDirectoryName(Globals.ThisAddIn.Application.ActiveWorkbook.FullName) + Path.DirectorySeparatorChar + "Out" + Path.DirectorySeparatorChar + "config";
29 | }
30 | }
31 |
32 |
33 | Dictionary templateDir = new Dictionary()
34 | {
35 | {"$Template$",new StringBuilder() },
36 | {"$FieldDefine$",new StringBuilder() },
37 | {"$ColCount$",new StringBuilder() },
38 | {"$CheckColName$",new StringBuilder() },
39 | {"$ReadBinColValue$",new StringBuilder() },
40 | {"$ReadCsvColValue$",new StringBuilder() },
41 | {"$InitPrimaryField$",new StringBuilder() },
42 | {"$PrimaryKey$",new StringBuilder() },
43 | {"$ReadJsonColValue$",new StringBuilder() },
44 | };
45 |
46 | string name = "";
47 | StringBuilder sb = new StringBuilder();
48 | public void Export(string fileName, List type, List key, List des)
49 | {
50 | string[] titles = fileName.Split('_');
51 | name = titles[0];
52 |
53 | templateDir["$Template$"].Append(name);
54 | templateDir["$PrimaryKey$"].Append(key[0]);
55 |
56 | AddField(templateDir["$FieldDefine$"], type, key,des);
57 |
58 | templateDir["$ColCount$"].Append(key.Count);
59 |
60 | CheckColName(templateDir["$CheckColName$"],key,name);
61 |
62 | ReadBinColValue(templateDir["$ReadBinColValue$"], type, key);
63 |
64 | ReadCsvColValue(templateDir["$ReadCsvColValue$"], type, key);
65 |
66 | InitPrimaryField(templateDir["$InitPrimaryField$"], templateDir["$PrimaryKey$"].ToString());
67 |
68 | ReadJsonColValue(templateDir["$ReadJsonColValue$"],type,key);
69 |
70 | string text = Resources.ConfigTemplate;
71 |
72 | foreach(var dir in templateDir)
73 | {
74 | text = text.Replace(dir.Key, dir.Value.ToString());
75 | }
76 |
77 |
78 | if(!Directory.Exists(CSPath))
79 | {
80 | Directory.CreateDirectory(CSPath);
81 | }
82 | string path = CSPath+ Path.DirectorySeparatorChar + name + ".cs";
83 | StreamWriter sw = new StreamWriter(path, false, Encoding.UTF8);
84 | sw.Write(text);
85 | sw.Flush();
86 | sw.Close();
87 |
88 | GenerateConfigLoad();
89 | }
90 |
91 | private void GenerateConfigLoad()
92 | {
93 | Dictionary dir = new Dictionary()
94 | {
95 | {"$loadConfItem$",new StringBuilder() },
96 | {"$fileCount$",new StringBuilder() }
97 | };
98 | int fileCount = 0;
99 | string[] files = Directory.GetFiles(Path.GetDirectoryName(WorkbookFullName));
100 | foreach (string s in files)
101 | {
102 | string file = Path.GetFileName(s).Split('_')[0];
103 | string suffix = ".json";
104 | if (!file.Contains('~'))
105 | {
106 | fileCount++;
107 | StringBuilder sb = dir["$loadConfItem$"];
108 | sb.AppendFormat(T2 + E("yield return StartCoroutine(LoadData(\"{0}" + suffix + "\"));"), file);
109 | sb.AppendFormat(T2 + E("{0}Table.Instance.LoadJson(textContent);"), file);
110 | sb.AppendFormat(T2 + E("Progress({0});"), fileCount);
111 | }
112 | }
113 | dir["$fileCount$"].Append(fileCount);
114 |
115 | string text = Resources.ConfigLoadTemplate;
116 | foreach (var d in dir)
117 | {
118 | text = text.Replace(d.Key, d.Value.ToString());
119 | }
120 | string path = CSPath + Path.DirectorySeparatorChar + "ConfigLoad.cs";
121 | StreamWriter sw = new StreamWriter(path, false, Encoding.UTF8);
122 | sw.Write(text);
123 | sw.Flush();
124 | sw.Close();
125 | }
126 |
127 | void ReadJsonColValue(StringBuilder sb, List type, List key)
128 | {
129 | for (int i = 0; i < key.Count; ++i)
130 | {
131 | switch (type[i])
132 | {
133 | case "I":
134 | sb.AppendFormat(T3 + E("member.{0} = (int)jd[\"{1}\"];"), key[i], key[i]);
135 | break;
136 | case "F":
137 | sb.AppendFormat(T3 + E("member.{0} = (float)((double)jd[\"{1}\"]);"), key[i], key[i]);
138 | break;
139 | case "B":
140 | sb.AppendFormat(T3 + E("member.{0} = (bool)jd[\"{1}\"];"), key[i], key[i]);
141 | break;
142 | case "S":
143 | sb.AppendFormat(T3 + E("member.{0} = (string)jd[\"{1}\"];"), key[i], key[i]);
144 | break;
145 | }
146 | }
147 | }
148 |
149 | void InitPrimaryField(StringBuilder sb, string key)
150 | {
151 | sb.AppendLine(T2 + key + " = 0;");
152 | sb.AppendLine(T2 + "IsValidate = false;");
153 | }
154 |
155 | void ReadCsvColValue(StringBuilder sb, List type, List key)
156 | {
157 | for (int i=0;i key,string name)
179 | {
180 | for (int i = 0; i < key.Count; ++i)
181 | {
182 | sb.AppendFormat(T2 + E("if(vecLine[{0}]!=\"{1}\") {{ Debug.Log(\"{2}.json中字段[{3}]位置不对应\"); return false; }}"),
183 | i, key[i], name, key[i], name);
184 | }
185 | sb.AppendLine();
186 | }
187 |
188 | void ReadBinColValue(StringBuilder sb,List type,List key)
189 | {
190 | for (int i = 0; i < key.Count; ++i)
191 | {
192 | switch (type[i])
193 | {
194 | case "I":
195 | sb.AppendFormat(T3 + E("readPos += HS_ByteRead.ReadInt32Variant(binContent, readPos, out member.{0} );"), key[i]);
196 | break;
197 | case "F":
198 | sb.AppendFormat(T3 + E("readPos += HS_ByteRead.ReadFloat(binContent, readPos, out member.{0} );"), key[i]);
199 | break;
200 | case "B":
201 | sb.AppendFormat(T3 + E("readPos += HS_ByteRead.ReadBool(binContent, readPos, out member.{0} );"), key[i]);
202 | break;
203 | case "S":
204 | sb.AppendFormat(T3 + E("readPos += HS_ByteRead.ReadString(binContent, readPos, out member.{0} );"), key[i]);
205 | break;
206 | }
207 |
208 | }
209 | }
210 |
211 |
212 | string E(string s="")
213 | {
214 | return s + "\r\n";
215 | }
216 |
217 | void AddTitle(StringBuilder sb,string title)
218 | {
219 | sb.AppendLine(T1 + "/// ");
220 | sb.AppendFormat(E(T1 + "/// {0}"), title);
221 | sb.AppendLine(T1 + "/// ");
222 | }
223 |
224 | ///
225 | /// 添加字段
226 | ///
227 | ///
228 | ///
229 | ///
230 | ///
231 | void AddField(StringBuilder sb,List type, List key, List des)
232 | {
233 | for(int i=0;i
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/ExportJson/fastJSON.cs:
--------------------------------------------------------------------------------
1 | using System.Collections.Generic;
2 | using System.Collections;
3 | using System.Data;
4 | using System.Globalization;
5 | using System.IO;
6 | using System.Reflection.Emit;
7 | using System.Reflection;
8 | using System.Text;
9 | using System;
10 |
11 | namespace fastJSON
12 | {
13 | internal static class Formatter
14 | {
15 | public static string Indent = " ";
16 |
17 | public static void AppendIndent(StringBuilder sb, int count)
18 | {
19 | for (; count > 0; --count) sb.Append(Indent);
20 | }
21 |
22 | public static bool IsEscaped(StringBuilder sb, int index)
23 | {
24 | bool escaped = false;
25 | while (index > 0 && sb[--index] == '\\') escaped = !escaped;
26 | return escaped;
27 | }
28 |
29 | public static string PrettyPrint(string input)
30 | {
31 | var output = new StringBuilder(input.Length * 2);
32 | char? quote = null;
33 | int depth = 0;
34 |
35 | for (int i = 0; i < input.Length; ++i)
36 | {
37 | char ch = input[i];
38 |
39 | switch (ch)
40 | {
41 | case '{':
42 | case '[':
43 | output.Append(ch);
44 | if (!quote.HasValue)
45 | {
46 | output.AppendLine();
47 | AppendIndent(output, ++depth);
48 | }
49 | break;
50 | case '}':
51 | case ']':
52 | if (quote.HasValue)
53 | output.Append(ch);
54 | else
55 | {
56 | output.AppendLine();
57 | AppendIndent(output, --depth);
58 | output.Append(ch);
59 | }
60 | break;
61 | case '"':
62 | case '\'':
63 | output.Append(ch);
64 | if (quote.HasValue)
65 | {
66 | if (!IsEscaped(output, i))
67 | quote = null;
68 | }
69 | else quote = ch;
70 | break;
71 | case ',':
72 | output.Append(ch);
73 | if (!quote.HasValue)
74 | {
75 | output.AppendLine();
76 | AppendIndent(output, depth);
77 | }
78 | break;
79 | case ':':
80 | if (quote.HasValue) output.Append(ch);
81 | else output.Append(" : ");
82 | break;
83 | default:
84 | if (quote.HasValue || !char.IsWhiteSpace(ch))
85 | output.Append(ch);
86 | break;
87 | }
88 | }
89 |
90 | return output.ToString();
91 | }
92 | }
93 | }
94 |
95 | namespace fastJSON
96 | {
97 | public sealed class DatasetSchema
98 | {
99 | public List Info { get; set; }
100 | public string Name { get; set; }
101 | }
102 | }
103 |
104 | namespace fastJSON
105 | {
106 | public delegate string Serialize(object data);
107 | public delegate object Deserialize(string data);
108 |
109 | public sealed class JSONParameters
110 | {
111 | ///
112 | /// Use the optimized fast Dataset Schema format (default = True)
113 | ///
114 | public bool UseOptimizedDatasetSchema = true;
115 | ///
116 | /// Use the fast GUID format (default = True)
117 | ///
118 | public bool UseFastGuid = true;
119 | ///
120 | /// Serialize null values to the output (default = True)
121 | ///
122 | public bool SerializeNullValues = true;
123 | ///
124 | /// Use the UTC date format (default = True)
125 | ///
126 | public bool UseUTCDateTime = true;
127 | ///
128 | /// Show the readonly properties of types in the output (default = False)
129 | ///
130 | public bool ShowReadOnlyProperties = false;
131 | ///
132 | /// Use the $types extension to optimise the output json (default = True)
133 | ///
134 | public bool UsingGlobalTypes = true;
135 | ///
136 | /// ** work in progress
137 | ///
138 | public bool IgnoreCaseOnDeserialize = false;
139 | ///
140 | /// Anonymous types have read only properties
141 | ///
142 | public bool EnableAnonymousTypes = false;
143 | ///
144 | /// Enable fastJSON extensions $types, $type, $map (default = True)
145 | ///
146 | public bool UseExtensions = true;
147 | ///
148 | /// Use escaped unicode i.e. \uXXXX format for non ASCII characters (default = True)
149 | ///
150 | public bool UseEscapedUnicode = true;
151 |
152 | public void FixValues()
153 | {
154 | if (UseExtensions == false) // disable conflicting params
155 | {
156 | UsingGlobalTypes = false;
157 | }
158 | }
159 | }
160 |
161 | public sealed class JSON
162 | {
163 | //public readonly static JSON Instance = new JSON();
164 | [ThreadStatic]
165 | private static JSON _instance;
166 |
167 | public static JSON Instance
168 | {
169 | get { return _instance ?? (_instance = new JSON()); }
170 | }
171 |
172 | private JSON()
173 | {
174 | }
175 | ///
176 | /// You can set these paramters globally for all calls
177 | ///
178 | public JSONParameters Parameters = new JSONParameters();
179 | private JSONParameters _params;
180 |
181 | public string ToJSON(object obj)
182 | {
183 | _params = Parameters;
184 | _params.FixValues();
185 | Reflection.Instance.ShowReadOnlyProperties = _params.ShowReadOnlyProperties;
186 | return ToJSON(obj, Parameters);
187 | }
188 |
189 | public string ToJSON(object obj, JSONParameters param)
190 | {
191 | _params = param;
192 | _params.FixValues();
193 | Reflection.Instance.ShowReadOnlyProperties = _params.ShowReadOnlyProperties;
194 | Type t = null;
195 |
196 | if (obj == null)
197 | return "null";
198 |
199 | if (obj.GetType().IsGenericType)
200 | t = obj.GetType().GetGenericTypeDefinition();
201 | if (t == typeof(Dictionary<,>) || t == typeof(List<>))
202 | _params.UsingGlobalTypes = false;
203 |
204 | // FEATURE : enable extensions when you can deserialize anon types
205 | if (_params.EnableAnonymousTypes) { _params.UseExtensions = false; _params.UsingGlobalTypes = false; Reflection.Instance.ShowReadOnlyProperties = true; }
206 | _usingglobals = _params.UsingGlobalTypes;
207 | return new JSONSerializer(_params).ConvertToJSON(obj);
208 | }
209 |
210 | public object Parse(string json)
211 | {
212 | _params = Parameters;
213 | Reflection.Instance.ShowReadOnlyProperties = _params.ShowReadOnlyProperties;
214 | return new JsonParser(json, _params.IgnoreCaseOnDeserialize).Decode();
215 | }
216 |
217 | public T ToObject(string json)
218 | {
219 | return (T)ToObject(json, typeof(T));
220 | }
221 |
222 | public object ToObject(string json)
223 | {
224 | return ToObject(json, null);
225 | }
226 |
227 | public object ToObject(string json, Type type)
228 | {
229 | _params = Parameters;
230 | _params.FixValues();
231 | Reflection.Instance.ShowReadOnlyProperties = _params.ShowReadOnlyProperties;
232 | Type t = null;
233 | if (type != null && type.IsGenericType)
234 | t = type.GetGenericTypeDefinition();
235 | if (t == typeof(Dictionary<,>) || t == typeof(List<>))
236 | _params.UsingGlobalTypes = false;
237 | _usingglobals = _params.UsingGlobalTypes;
238 |
239 | object o = new JsonParser(json, Parameters.IgnoreCaseOnDeserialize).Decode();
240 | if (o == null)
241 | return null;
242 |
243 | #if !SILVERLIGHT
244 | if (type != null && type == typeof(DataSet))
245 | return CreateDataset(o as Dictionary, null);
246 |
247 | if (type != null && type == typeof(DataTable))
248 | return CreateDataTable(o as Dictionary, null);
249 | #endif
250 | if (o is IDictionary)
251 | {
252 | if (type != null && type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Dictionary<,>)) // deserialize a dictionary
253 | return RootDictionary(o, type);
254 | else // deserialize an object
255 | return ParseDictionary(o as Dictionary, null, type, null);
256 | }
257 |
258 | if (o is List