我在尝试使用 Dart 中的 Build Runner 生成 Json 可序列化生成器时遇到问题。首先,我尝试运行flutter packages pub run build_runner build来生成 Json Serialized,但它表明它存在冲突问题。所以我运行 command --delete-conflicting-outputs来解决冲突的问题。
之后我尝试flutter packages pub run build_runner build再次运行以重新生成 Json 值。但我得到的结果是这样的:
所以输出是:[INFO] Succeeded after 137ms with 0 outputs (0 actions)
我因此感到压力很大,因为所有生成的文件都被删除了。有人可以告诉我发生了什么事以及如何解决这个问题吗?
我已经到处检查但仍然没有找到答案。
在我的项目中有 java 和 kotlin 模块。在某些 kotlin 模块中,我需要自定义序列化。所有长值都应序列化为字符串。我用杰克逊。
例子:
科特林
data class KotlinRecord(val id: Long)
Run Code Online (Sandbox Code Playgroud)
爪哇
public class JavaRecord {
private Long id;
public Long getId() {
return id;
}
public JavaRecord setId(Long id) {
this.id = id;
return this;
}
}
Run Code Online (Sandbox Code Playgroud)
当在java模块中配置 ObjectMapper并序列化值时,如下所示:
ObjectMapper mapper = new ObjectMapper()
.registerModule(new KotlinModule())
.registerModule(new JavaTimeModule())
.registerModule(
new SimpleModule()
.addSerializer(Long.class, LongToStringJSONSerializer.ofObject())
.addSerializer(long.class, LongToStringJSONSerializer.ofPrimitive())
);
JavaRecord javaRecord = new JavaRecord().setId(Long.MAX_VALUE);
KotlinRecord kotlinRecord = new KotlinRecord(Long.MAX_VALUE);
System.out.println("Java record: " + mapper.writeValueAsString(javaRecord));
System.out.println("Kotlin record: " + …Run Code Online (Sandbox Code Playgroud) 我正在尝试将此 JSON 响应反序列化为一个对象,并且我的一个键上有一个连字符。不幸的是,Kotlin 不支持变量名称中的连字符,这就是我使用 @SerializedName() 但它现在仍然有效的原因。有什么线索可以解释为什么吗?
JSON 响应
[
{
"dateCreated": "07-22-2021",
"comments": "Comment",
"vehicle_type": "Sedan",
"name": "Leagacy Nissan Template",
"template-type": "", //this is giving me the problem
"template_uses_type": "Both"
...
}
]
Run Code Online (Sandbox Code Playgroud)
我的对象:
@Serializable
data class SpinDataResponse(
val dateCreated:String,
val comments: String,
val vehicle_type:String,
val name:String,
@SerializedName("template-type") val template_type:String,
val template_uses_type:String,
...
)
Run Code Online (Sandbox Code Playgroud)
错误:
I/System.out:错误:偏移量 120 处出现意外的 JSON 令牌:遇到未知密钥“模板类型”。在“Json {}”构建器中使用“ignoreUnknownKeys = true”来忽略未知键。JSON 输入:.....“名称”:“Nissan PathFinder”,“模板类型”:“”,“template_.....
我不想忽略未知的密钥,因为我实际上需要它。
我试图将一堆XML文件解析为一个已经正常工作的JSON文件.
最终的JSON文件如下所示:
{
"items": [
{
"subItems": [
{
"Name": "Name",
"Value": "Value",
"Type": "text"
},
{
"Name": "Name",
"Value": "Value",
"Type": "text"
}
]
},
{
"subItems": [
{
"Name": "Name",
"Value": "Value",
"Type": "text"
},
{
"Name": "Name",
"Value": "Value",
"Type": "text"
},
...
Run Code Online (Sandbox Code Playgroud)
相反,我想实现以下结构:
{
"items": [
[
{
"Name": "Name",
"Value": "Value",
"Type": "text"
},
{
"Name": "Name",
"Value": "Value",
"Type": "text"
}
],
[
{
"Name": "Name",
"Value": "Value",
"Type": "text"
},
{
"Name": "Name", …Run Code Online (Sandbox Code Playgroud) 根据json_serializable软件包安装说明,您应该添加以下依赖项:
dependencies:
json_serializable: ^2.0.3
Run Code Online (Sandbox Code Playgroud)
这是我的代码:
import 'package:json_annotation/json_annotation.dart';
part 'person.g.dart';
@JsonSerializable(nullable: false)
class Person {
final String firstName;
final String lastName;
final DateTime dateOfBirth;
Person({this.firstName, this.lastName, this.dateOfBirth});
factory Person.fromJson(Map<String, dynamic> json) => _$PersonFromJson(json);
Map<String, dynamic> toJson() => _$PersonToJson(this);
}
Run Code Online (Sandbox Code Playgroud)
现在在Flutter中运行它:
flutter packages pub run build_runner build
Run Code Online (Sandbox Code Playgroud)
或针对Dart项目:
pub run build_runner build
Run Code Online (Sandbox Code Playgroud)
我收到以下错误:
找不到软件包“ build_runner”。您忘记添加依赖项了吗?
怎么了?
我试图解析 json,将其打印到控制台,然后放入 ListView.builder 并收到此错误:类型 '_InternalLinkedHashMap<String,dynamic>' 不是类型 'String' 的子类型
我如何解决它?
列出数据
FutureBuilder(
future: restaurantSearch,
builder: (context, AsyncSnapshot<RestaurantSearch> snapshot) {
if(snapshot.connectionState == ConnectionState.waiting) {
return Expanded(child: Center(child: CircularProgressIndicator(strokeWidth: 3)));
} else if(snapshot.connectionState == ConnectionState.done) {
if(snapshot.hasData) {
return ListView.builder(
shrinkWrap: true,
itemCount: snapshot.data.restaurants.length,
itemBuilder: (context, index) {
var restaurant = snapshot.data.restaurants[index];
return ListTile(
title:Text(restaurant.name),
);
}
);
}
} else if (snapshot.hasError) {
return Center(child: Text(snapshot.error.toString()));
}
return Text('');
}
)
Run Code Online (Sandbox Code Playgroud)
api服务
Future<RestaurantSearch> restaurantSearch(String query) async {
final response = await dio.get("https://restaurant-api.dicoding.dev/search", …Run Code Online (Sandbox Code Playgroud) 是否可以修改 json 序列化和反序列化,使结构如下:
type Foo struct {
A int64
B uint64
// and other stuff with int64 and uint64 and there's a lot of struct that are like this
}
x := Foo{A: 1234567890987654, B: 987654321012345678}
byt, err := json.Marshal(x)
fmt.Println(err)
fmt.Println(string(byt))
// 9223372036854775808 9223372036854775808
err = json.Unmarshal([]byte(`{"A":"12345678901234567", "B":"98765432101234567"}`), &x)
// ^ must be quoted since javascript can't represent those values properly (2^53)
// ^ json: cannot unmarshal string into Go struct field Foo.A of type int64
fmt.Println(err)
fmt.Printf("%#v\n", x) …Run Code Online (Sandbox Code Playgroud) 我在我的应用程序中使用Ktor 序列化,下面是build.gradle中的依赖项:
dependencies {
// ...
implementation "io.ktor:ktor-serialization:$ktor_version"
}
Run Code Online (Sandbox Code Playgroud)
并在Application.kt中进行设置:
fun main(args: Array<String>): Unit = io.ktor.server.netty.EngineMain.main(args)
@Suppress("unused")
fun Application.module(@Suppress("UNUSED_PARAMETER") testing: Boolean = false) {
// ...
install(ContentNegotiation) {
json(Json {
prettyPrint = true
})
}
// ...
}
Run Code Online (Sandbox Code Playgroud)
一切都很完美,但枚举......例如,我有下一个:
enum class EGender(val id: Int) {
FEMALE(1),
MALE(2);
companion object {
fun valueOf(value: Int) = values().find { it.id == value }
}
}
Run Code Online (Sandbox Code Playgroud)
如果我序列化这个枚举实例,Ktor将输出如下内容:
{
"gender": "MALE"
}
Run Code Online (Sandbox Code Playgroud)
如何在不重命名枚举成员的情况下将其改成小写?
PS另外,我无法更改Int类型String,因为它代表数据库 …
我有一个带有 JPA 和 JSON 序列化的 Spring-Boot-Project。我尝试使用 @JsonView 仅序列化指定的属性。它工作正常,但对于我在Order(例如order.user)中的关联,它序列化了空的 Json-Object。
我使用以下依赖项
请参阅以下 Json 结果:
{
"content" : {
"orderResources" : [ {
"receiptDate" : "2019-08-14",
"state" : "BILL_CREATED",
"user" : { },
"employer" : { },
"orderplace" : { },
"propertyManagement" : null,
"plannings" : [ { } ]
}, {
"receiptDate" : "2019-08-17",
"state" : "BILL_CREATED",
"user" : { },
"employer" : { },
"orderplace" : { },
"propertyManagement" : …Run Code Online (Sandbox Code Playgroud)