How to deserialize json using serde_with for double option [closed] - json

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 16 days ago.
This post was edited and submitted for review 14 days ago.
Improve this question
I am using serde_with = "2.2.0" trying to deserialize this json body:
#[derive(Deserialize, Debug)]
pub struct UpdatePartialTask {
#[serde(
default, // deserialization
skip_serializing_if = "Option::is_none",// serialization
with = "::serde_with::rust::double_option",
)]
pub priority: Option<Option<String>>,
#[serde(
default,// deserialization
skip_serializing_if = "Option::is_none",// serialization
with = "::serde_with::rust::double_option",
)]
pub user_id: Option<Option<i32>>,
#[serde(
default,// deserialization
skip_serializing_if = "Option::is_none",//serialization
with = "::serde_with::rust::double_option",
)]
pub title: Option<String>,
}
then I get this error:
error[E0308]: mismatched types
--> src/routes/route_func.rs:309:10
|
309 | #[derive(Deserialize, Debug)]
| ^^^^^^^^^^^ expected struct `std::string::String`, found enum `std::option::Option`
|
= note: expected enum `std::option::Option<std::string::String>`
found enum `std::option::Option<std::option::Option<_>>`
= note: this error originates in the macro `try` (in Nightly builds, run with -Z macro-backtrace for more info)

Thanks #kmdreko
I found out that one field below my user_id field above has only one option(which should not use serde_with on this field):
pub title: Option<String>,
but it should be a double option if using with serde_with on this field:
pub title: Option<Option<String>>,

Related

Anonymous structs outside function not working [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I don't understand why this doesn't work for this type of structure.
package main
import (
"fmt"
)
var myStruct struct {
number float64
word string
toggle bool
}
myStruct.number = 3.14
myStruct.word = "pie"
myStruct.toggle = true
func main() {
//myStruct.number = 3.14
//myStruct.word = "pie"
//myStruct.toggle = true
fmt.Println(myStruct.number)
fmt.Println(myStruct.toggle)
fmt.Println(myStruct.word)
}
If I try to change myStruct.number outside main, I get a compilation error syntax error: non-declaration statement outside function body, but it works fine inside the function. With variables or other types of data structures, it works fine to change values outside main scope, but not with struct.
The program is an example from Head first Go, and even if I searched at least three more books and google for more information, I haven't found something similar that would be better explained.
https://play.golang.org/p/brocZzWuRae
package main
import (
"fmt"
)
var myStruct = struct {
number float64
word string
toggle bool
}{
number: 3.14,
word: "pie",
toggle: true,
}
func main() {
//myStruct.number = 3.14
//myStruct.word = "pie"
//myStruct.toggle = true
fmt.Println(myStruct.number)
fmt.Println(myStruct.toggle)
fmt.Println(myStruct.word)
}

Swift - crash EXC_BAD_ACCESS JSONDecoder with large JSON [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I'm stuck on decoding a JSON in swift.
I've got the following code in a playground with a JSON that has 10 fields. When i try to decode the data I get the following Error
error: Execution was interrupted, reason: EXC_BAD_ACCESS (code=EXC_I386_GPFLT).
The process has been left at the point where it was interrupted, use "thread return -x" to return to the state before expression evaluation.
But this error does not seem to happen if I take out e.g. "ninth" and "tenth" or 2 of any of the other fields so only 8 fields remain in the struct.
Is there a limitation of only be able to have 8 fields decoded? Am I missing something?
is there anything i can do to overcome this issue?
My code snippet:
let decoder = JSONDecoder()
struct Positions: Codable {
let first : String
let second: String
let third: String
let forth: String
let fith: String
let sixth: String
let seventh: String
let eigth: String
let nineth: String
let tenth: String
}
var positions = """
{
"first" : "first",
"second": "second",
"third": "third",
"forth": "forth",
"fith": "fith",
"sixth": "sixth",
"seventh": "seventh",
"eigth": "eigth",
"nineth": "nineth",
"tenth": "tenth"
}
""".data(using: .utf8)
let result = try decoder.decode(Positions.self, from: positions!)
print("tr \(result)")

Add an object into JSON array with Go [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I've got a JSON file called 'books.json' looking like this:
{"Books":
[
]
}
and I'd like to add something like this into the array using Go:
{
"Title": "Lord of the Rings",
"Author: "J. R. Tolkien",
"Language: "English"
}
Create a struct to hold your data:
type Book struct {
Title string `json:"Title"`
Author string `json:"Author"`
Language string `json:"Language"`
}
type Library struct {
Books []Book `json:"Books"`
}
Unmarshal existing JSON to the struct:
in := `{"Books": []}`
var library Library
json.Unmarshal([]byte(in), &library)
Append a new Book:
newBook := Book{
Title: "Lord of the Rings",
Author: "J.R. Tolkien",
Language: "English",
}
library.Books = append(library.Books, newBook)
Marshal back to JSON and check the result:
j, _ := json.Marshal(library)
fmt.Println(string(j))
Entire code on Go Playground: https://play.golang.org/p/v24dKorFpK5

Swift 4: JSONDecoder fails in one specific case - "The operation could not be completed" [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
I am receiving JSON text, converting it to Data, and then using JSONDecoder to create a concrete type represented by the JSON text/string.
It does work with my "complex" data structure (which implements Codable), or even a simple array of Int as shown below:
import Foundation
let jsonTextContainigArrayOfInt: String = "[1,2,3]"
let data = jsonTextContainigArrayOfInt.data(using: .utf8)!
do {
let arrayOfInt: [Int] = try JSONDecoder().decode([Int].self, from: data)
for n in arrayOfInt {
print(n)
}
}
catch {
print(error)
}
The previous code works and correctly creates the array of Int and prints them.
The problem occurs when doing this same approach with a single Int in the JSON-text:
import Foundation
let jsonTextContainigOneInt: String = "1"
let data = jsonTextContainigOneInt.data(using: .utf8)!
do {
let myInt: Int = try JSONDecoder().decode(Int.self, from: data)
print(myInt)
}
catch {
print(error)
}
For this second approach, I get the following error:
"The operation could not be completed"
*** Edit ***
Bug report for this already exists: https://bugs.swift.org/browse/SR-6163
JSONDecoder can only decode a collection type (array or dictionary) as root object.
Under the hood JSONDecoder uses JSONSerialization without any options. However to decode a String or Int you have to specify the .allowFragments option.
Use JSONSerialization with the .allowFragments option
let jsonTextContainingOneString = "1"
let data = Data(jsonTextContainingOneString.utf8)
do {
let myString = try JSONSerialization.jsonObject(with: data, options: .allowFragments)
print(myString)
}
catch {
print(error)
}
Interesting... I found this:
https://github.com/apple/swift-corelibs-foundation/blob/master/Foundation/JSONSerialization.swift#L120
Specifically this guard statement:
open class JSONSerialization : NSObject {
//...
// top level object must be an Swift.Array or Swift.Dictionary
guard obj is [Any?] || obj is [String: Any?] else {
return false
}
//...
}
Then I looked if a simple text-string should be considered valid JSON, and apparently it should now (it was previously not accepted as valid JSON). At least, based on this excellent answer: https://stackoverflow.com/a/7487892/8284660
This makes me wonder whether or not the behavior on my original post should be a bug or not.

How do you design a codable JSON field which can be either an empty string or an int [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
How do you handle a field of a codable struct from JSON which can be either an empty string or an int? I tried using the data type any but that does not conform to codable. I think that if it does not have a value then it returns an empty string or otherwise, it returns an int. I am using Swift 4 and XCode 9. Thanks in advance
I really would suggest changing that web service to return values consistently (and if there is no value for the integer type, don't return anything for that key).
But if you're stuck with this design, you will have to write your own init(from:) which gracefully handles the failure to parse the integer value. E.g.:
struct Person: Codable {
let name: String
let age: Int?
init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
name = try values.decode(String.self, forKey: .name)
do {
age = try values.decode(Int.self, forKey: .age)
} catch {
age = nil
}
}
}
I'd also advise against using 0 as a sentinel value for "no integer value provided". This is what optionals are for.