我有一个结构为:
的JSON文件Arrow
我想把它转换成结构的字典(或任何有用的东西):
import javax.swing.JApplet;
import java.util.*;
import java.awt.*;
public class Shapes extends JApplet
{
public void paint (Graphics page)
{
resize(400,300);
Random rand = new Random();
// Declare size constants
final int circleMax = 160,circleMin = 40; // circle max and min diameter
final int locMaxX = 360, locMaxY = 260;
int radiusSize = 0, locationx = 0,locationy = 0 ;
// Declare variables
radiusSize = (rand.nextInt(circleMax)+ circleMin);
locationx =20 ;//rand.nextInt(locMaxX)+ 20;
locationy =20 ;// rand.nextInt(locMaxY) + 20;
// Draw the circle 1
page.drawOval(locationx, locationy, radiusSize,radiusSize);
}
}
我正在尝试以下方法:
[ {"unit_id": {"type":[string],"customer_id":[int]} },
...,
...]
哪个失败,因为该文件无法反序列化为该结构。我也尝试过创建一个类:
Dictionary<int,Tuple<string,int>>
然后:
Dictionary<int, Tuple<string,int>> units =
JsonConvert.DeserializeObject<Dictionary<int, Tuple<string, int>>>
(File.ReadAllText(jsonFile));
哪个没有失败,但没有用任何值填充列表。
由于
答案 0 :(得分:2)
对于您的JSON结构,您可能需要创建如下类:
class Unit
{
public CustomerType UnitId;
}
class CustomerType
{
public int CustomId { get; set; }
public string Type { get; set; }
}
或使用dynamic
:
Unit unit = new Unit();
unit.UnitId = new CustomerType()
{
CustomId = 1001,
Type = "Customer"
};
//generate test json string
string jsonTest = JsonConvert.SerializeObject(unit);
//convert to dynamic
var result = JsonConvert.DeserializeObject<dynamic>(jsonTest);
Console.WriteLine(result.UnitId.CustomId);
Console.WriteLine(result.UnitId.Type);
答案 1 :(得分:0)
所以我设法使用以下(杂乱的)代码创建我的字典:
public static Dictionary<int, Tuple<string, int>> parseJsonIntoDictionary(string jsonFile) {
Dictionary<int, Tuple<string, int>> unitDictionary = new Dictionary<int,Tuple<string,int>>();
var json = System.IO.File.ReadAllText(jsonFile);
var units = JArray.Parse(json);
foreach (JToken unit in units) {
JProperty property = ((JObject)unit).Properties().ToArray()[0];
int unitID = Convert.ToInt32(property.Name);
Tuple<string,int> tempTuple = new Tuple<string,int>(Convert.ToString(unit[property.Name]["unit_type"]),Convert.ToInt32(unit[property.Name]["customer_id"]));
unitDictionary[unitID] = tempTuple;
}
return unitDictionary;
}