我有一个json字符串,我想解析成一个对象[]:
{ "Thing":"Thing","That":{"Item1":15,"Item2":"Moo","Item3":{"Count":27,"Type":"Frog"}}}
Run Code Online (Sandbox Code Playgroud)
生成的匿名对象数组需要包含原始json对象的每个属性.我的问题是JsonConvert.DeserializeObject返回一种JContainer或JObject.我无法找到返回普通香草c#对象的方法.
这是我之前尝试过的一系列非功能性代码.我不必使用JSON.net,但我想尽可能确保与生成json的代码兼容.
JObject deserialized = JsonConvert.DeserializeObject<JObject>(dataString);
object[] data =
deserialized.Children().Where(x => x as JProperty != null).Select(x => x.Value<Object>()).ToArray();
Run Code Online (Sandbox Code Playgroud)
更新
我正在使用生成的对象数组通过反射调用方法.解析的json对象的类型在运行时是未知的.问题的关键在于JObject或JContainer对象类型与被调用方法的签名不匹配.动态具有相同的副作用.正在调用方法如下:
Type _executionType = typeof(CommandExecutionDummy);
CommandExecutionDummy provider = new CommandExecutionDummy();
var method = _executionType.GetMethod(model.Command,
BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public | BindingFlags.Static);
if (method == null)
throw new InvalidCommandException(String.Format("Invalid Command - A command with a name of {0} could not be found", model.Command));
return method.Invoke(provider, model.CommandData);
Run Code Online (Sandbox Code Playgroud) 我尝试编写自定义jackson反序列化器.我希望"查看"一个字段并对类执行自动反序列化,请参阅下面的示例:
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.ObjectCodec;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonNode;
import com.mypackage.MyInterface;
import com.mypackage.MyFailure;
import com.mypackage.MySuccess;
import java.io.IOException;
public class MyDeserializer extends JsonDeserializer<MyInterface> {
@Override
public MyInterface deserialize(JsonParser jp, DeserializationContext ctxt)
throws IOException, JsonProcessingException {
ObjectCodec codec = jp.getCodec();
JsonNode node = codec.readTree(jp);
if (node.has("custom_field")) {
return codec.treeToValue(node, MyFailure.class);
} else {
return codec.treeToValue(node, MySuccess.class);
}
}
}
Run Code Online (Sandbox Code Playgroud)
的POJO:
public class MyFailure implements MyInterface {}
public class MySuccess implements MyInterface {}
@JsonDeserialize(using = MyDeserializer.class)
public interface MyInterface …Run Code Online (Sandbox Code Playgroud) 我从一个看起来像这样的API获得JSON:
{
"Items": {
"Item322A": [{
"prop1": "string",
"prop2": "string",
"prop3": 1,
"prop4": false
},{
"prop1": "string",
"prop2": "string",
"prop3": 0,
"prop4": false
}],
"Item2B": [{
"prop1": "string",
"prop2": "string",
"prop3": 14,
"prop4": true
}]
},
"Errors": ["String"]
}
Run Code Online (Sandbox Code Playgroud)
我已经尝试了一些方法来在c#对象中表示这个JSON(这里列出的太多了).我已尝试过列表和词典,这是我最近尝试如何表示它的一个例子:
private class Response
{
public Item Items { get; set; }
public string[] Errors { get; set; }
}
private class Item
{
public List<SubItem> SubItems { get; set; }
}
private class SubItem
{
public List<Info> Infos { get; …Run Code Online (Sandbox Code Playgroud) 我有如下JSON数据:
{
"Address": {
"House_Number": 2,
"State": "MA",
"Street_Number": 13
},
"Name": "John"
}
Run Code Online (Sandbox Code Playgroud)
我想将它加载到如下定义的类中:
class Address:
def __init__(self):
self.House_Number = 0
class Employee:
def __init__(self):
self.Name = ''
self.Address = Address()
Run Code Online (Sandbox Code Playgroud)
如果我使用类Employee如object_hook,然后它使用两个物体的相同类(具有外部对象Name和Address作为成员和内部具有对象成员House_Number等).
基本上,如果e是加载JSON数据的对象,那么
type(e.Address)应该Address不是Employee.
有没有办法将这个JSON数据加载到Employee维护类层次结构的类中?层次结构可以任意深入.
考虑下面的示例程序
var calendar = new Calendar
{
Id = 42,
CoffeeProvider = "Espresso2000",
Meetings = new[]
{
new Meeting
{
Location = "Room1",
From = DateTimeOffset.Parse("2014-01-01T00:00:00Z"),
To = DateTimeOffset.Parse("2014-01-01T01:00:00Z")
},
new Meeting
{
Location = "Room2",
From = DateTimeOffset.Parse("2014-01-01T02:00:00Z"),
To = DateTimeOffset.Parse("2014-01-01T03:00:00Z")
},
}
};
var patch = @"{
'coffeeprovider': null,
'meetings': [
{
'location': 'Room3',
'from': '2014-01-01T04:00:00Z',
'to': '2014-01-01T05:00:00Z'
}
]
}";
var patchedCalendar = Patch(calendar, patch);
Run Code Online (Sandbox Code Playgroud)
该Patch()方法的结果应该等于calendar除了改变之外patch.那意味着; Id将是不变的,CoffeeProvider将被设置为null …
我正在使用新的firebase sdk for android并使用真正的数据库功能.当我使用getValue(simple.class)一切都很好.但是当我想解析一个子类的类时,母类的所有属性都是null,并且我有这种类型的错误:
在类uk.edume.edumeapp.TestChild上找不到名称的setter/field
public class TestChild extends TestMother {
private String childAttribute;
public String getChildAttribute() {
return childAttribute;
}
}
public class TestMother {
protected String motherAttribute;
protected String getMotherAttribute() {
return motherAttribute;
}
}
Run Code Online (Sandbox Code Playgroud)
这个功能
snapshot.getValue(TestChild.class);
Run Code Online (Sandbox Code Playgroud)
motherAttribute属性是null,我得到
在类uk.edume.edumeapp.TestChild上找不到关于motherAttribute的setter/field
我解析的Json是:
{
"childAttribute" : "attribute in child class",
"motherAttribute" : "attribute in mother class"
}
Run Code Online (Sandbox Code Playgroud) java android jackson json-deserialization firebase-realtime-database
在程序开始时,我从文件中读取数据:
let file = std::fs::File::open("data/games.json").unwrap();
let data: Games = serde_json::from_reader(file).unwrap();
Run Code Online (Sandbox Code Playgroud)
我想知道如何在编译时执行此操作,原因如下:
我可能还需要提到的是,数据只能读取,这意味着解决方案可以将其存储为静态。
我有一个员工表
public class Employee
{
[Key]
public long ID { get; set; }
public DateTime EmpDate { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
我创建了 Web API 来发布员工数据:
[HttpPost]
public async Task<ActionResult<Employee>> PostLead(Employee employee)
{
//Code to post
}
Run Code Online (Sandbox Code Playgroud)
这是我的 JSON 正文
{
"firstname":"xyz",
"lastname":"abc",
"EmpDate":"2019-01-06 17:16:40"
}
Run Code Online (Sandbox Code Playgroud)
我收到错误消息The JSON value could not be converted to System.DateTime.但是当我将EmpDate值作为传递时2019-01-06,我没有收到错误消息。
我试图将Cucumber的Json输出转换为单个Java对象.这包含嵌套四层深度的对象,我无法反序列化它.我现在正在使用杰克逊,但愿意接受建议.这是我的Json代码:
{
"line": 1,
"elements": [
{
"line": 3,
"name": "Converteren centimeters naar voeten/inches",
"description": "",
"id": "applicatie-neemt-maten-in-cm-en-converteert-ze-naar-voet/inch,-en-vice-versa;converteren-centimeters-naar-voeten/inches",
"type": "scenario",
"keyword": "Scenario",
"steps": [
{
"result": {
"duration": 476796588,
"status": "passed"
},
"line": 4,
"name": "maak Maten-object aan met invoer in \"centimeters\"",
"match": {
"arguments": [
{
"val": "centimeters",
"offset": 37
}
],
"location": "StepDefinition.maakMatenObjectAanMetInvoerIn(String)"
},
"keyword": "Given "
},
{
"result": {
"duration": 36319,
"status": "passed"
},
"line": 5,
"name": "ik converteer",
"match": {
"location": "StepDefinition.converteerMaten()"
},
"keyword": "When …Run Code Online (Sandbox Code Playgroud) 我正在尝试解码Firebase DataSnapshot中的数据,以便可以使用JSONDecoder对其进行解码.
当我使用URL通过网络请求访问它(获取Data对象)时,我可以正确解码此数据.
不过,我想用火力地堡API直接获取数据,使用observeSingleEvent上描述这个页面.
但是,当我这样做时,我似乎无法将结果转换为Data对象,我需要使用JSONDecoder.
是否可以使用DataSnapshot进行新的JSON解码?这怎么可能?我似乎无法弄明白.