How to Decode a JSON String

How to decode a JSON string in PHP?

print_r is your friend for figuring out JSON structure.

<?php

$addresses = json_decode('{"addresses":{"address":[{"@array":"true","@id":"888888","@uri":"xyz","household":{"@id":"44444","@uri":"xyz"},"person":{"@id":"","@uri":""},"addressType":{"@id":"1","@uri":"xyz","name":"Primary"},"address1":"xyz","address2":null,"address3":null,"city":"xyz","postalCode":"111111"}]}}');

$_SESSION['address1'] = $addresses->addresses->address[0]->address1;
$_SESSION['address2'] = $addresses->addresses->address[0]->address2;
$_SESSION['address3'] = $addresses->addresses->address[0]->address3;
$_SESSION['city'] = $addresses->addresses->address[0]->city;
$_SESSION['postalCode'] = $addresses->addresses->address[0]->postalCode;

print_r($_SESSION);

Results in:

Array
(
[address1] => xyz
[address2] =>
[address3] =>
[city] => xyz
[postalCode] => 111111
)

Decode JSON string containing JSON string

Represent your json like that:

{
"label": "Side",
"options": "[{ 'key': 'left', 'value': '0'},{ 'key':'right', 'value':1}]"
}

inside json with single quotes

let's assume you have this two classes :

public class YourObject
{
public string label { get; set; }
public string options { get; set; }
}
public class InsideObject
{
public string key { get; set; }
public int value { get; set; }
}

so your json has another json as as string under the key "options" and you can extract both of them like that:

 string json = "{\"label\": \"Side\", \"options\": \"[{ 'key': 'left', 'value': '0'},{ 'key':'right', 'value':1}]\"}";
var jsonObj = JsonConvert.DeserializeObject<YourObject>(json);
var insideObj = JsonConvert.DeserializeObject<InsideObject>(jsonObj.options);

P.S
here used Newtonsoft

Decode JSON string in Java with json-simple library

This is the best and easiest code:

public class test
{
public static void main(String str[])
{
String jsonString = "{\"stat\": { \"sdr\": \"aa:bb:cc:dd:ee:ff\", \"rcv\": \"aa:bb:cc:dd:ee:ff\", \"time\": \"UTC in millis\", \"type\": 1, \"subt\": 1, \"argv\": [{\"type\": 1, \"val\":\"stackoverflow\"}]}}";
JSONObject jsonObject = new JSONObject(jsonString);
JSONObject newJSON = jsonObject.getJSONObject("stat");
System.out.println(newJSON.toString());
jsonObject = new JSONObject(newJSON.toString());
System.out.println(jsonObject.getString("rcv"));
System.out.println(jsonObject.getJSONArray("argv"));
}
}

The library definition of the json files are given here. And it is not same libraries as posted here, i.e. posted by you. What you had posted was simple json library I have used this library.

You can download the zip. And then create a package in your project with org.json as name. and paste all the downloaded codes there, and have fun.

I feel this to be the best and the most easiest JSON Decoding.

Swift - How can I decode json string response into a String?

You need to convert the String to Data first to decode it using JSONDecoder:

let jsonResponse = " \"This is a response\" "
let data = Data(jsonResponse.utf8)
let str = try! JSONDecoder().decode(String.self, from: data)
print(str)

How to decode json string as UTF-8?

Just an aside first: UTF-8 is typically an external format, and typically represented by an array of bytes. It's what you might send over the network as part of an HTTP response. Internally, Dart stores strings as UTF-16 code points. The utf8 encoder/decoder converts between internal format strings and external format arrays of bytes.

This is why you are using utf8.decode(response.bodyBytes); taking the raw body bytes and converting them to an internal string. (response.body basically does this too, but it chooses the bytes->string decoder based on the response header charset. When this charset header is missing (as it often is) the http package picks Latin-1, which obviously doesn't work if you know that the response is in a different charset.) By using utf8.decode yourself, you are overriding the (potentially wrong) choice being made by http because you know that this particular server always sends UTF-8. (It may not, of course!)

Another aside: setting a content type header on a request is rarely useful. You typically aren't sending any content - so it doesn't have a type! And that doesn't influence the content type or content type charset that the server will send back to you. The accept header might be what you are looking for. That's a hint to the server of what type of content you'd like back - but not all servers respect it.

So why are your special characters still incorrect? Try printing utf8.decode(response.bodyBytes) before decoding it. Does it look right in the console? (It very useful to create a simple Dart command line application for this type of issue; I find it easier to set breakpoints and inspect variables in a simple ten line Dart app.) Try using something like Wireshark to capture the bytes on the wire (again, useful to have the simple Dart app for this). Or try using Postman to send the same request and inspect the response.

How are you trying to show the characters. If may simply be that the font you are using doesn't have them.

Decode html string from json

The JSON seems incorrect. There seems to be a missing " at the end of the value of "content":.

EDIT:

After your update, I took another look. You need to escape double quotes in a string. Weirdly enough, in this case (when the JSON is in a multi-line string), you need to escape the escaping character as well (i.e. \\) to decode the JSON properly and get a string you can work with.

Example:

import UIKit

let json = """
{
"id": 5,
"title": "iOS and iPadOS 14: The MacStories Review",
"content": "<div id=\\"readability-page-1\\" class=\\"page\\">test<div>"
}

"""

struct ArticleModel: Codable, Identifiable {
let id: Int
let title: String
let content: String
}

let jsonData = json.data(using: .utf8)!
let article = try JSONDecoder().decode(ArticleModel.self, from: jsonData)
print(article) // ArticleModel(id: 5, title: "iOS and iPadOS 14: The MacStories Review", content: "<div id=\"readability-page-1\" class=\"page\">test<div>")

By the way, https://app.quicktype.io/ is a great tool to get decoders (and encoders) for your JSON.

Swift: Decode JSON response and store nested JSON as String or JSON

As others have already said, you cannot just keep a part without decoding. However, decoding unknown data is trivial:

enum RawJsonValue {
case boolean(Bool)
case number(Double)
case string(String)
case array([RawJsonValue?])
case object([String: RawJsonValue])
}

extension RawJsonValue: Codable {
init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()

if let boolValue = try? container.decode(Bool.self) {
self = .boolean(boolValue)
} else if let numberValue = try? container.decode(Double.self) {
self = .number(numberValue)
} else if let stringValue = try? container.decode(String.self) {
self = .string(stringValue)
} else if let arrayValue = try? container.decode([RawJsonValue?].self) {
self = .array(arrayValue)
} else {
let objectValue = try container.decode([String: RawJsonValue].self)
self = .object(objectValue)
}
}

func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()

switch self {
case .boolean(let boolValue):
try container.encode(boolValue)
case .number(let numberValue):
try container.encode(numberValue)
case .string(let stringValue):
try container.encode(stringValue)
case .array(let arrayValue):
try container.encode(arrayValue)
case .object(let objectValue):
try container.encode(objectValue)
}
}
}

Now we can safely decode and convert to JSON string if needed:

struct Registration: Codable {
public enum State: String, Codable {
case provisioning, provisioned
}

let id, deviceType: String
let state: State
let error: String?
let thingUUID: Int?
let discoveryTimeout, installationTimeout: Int
let configurationPayload: RawJsonValue?
}

let jsonData = """
{
"id": "0000-0000-0000-0000-000",
"device_type": "device",
"state": "provisioning",
"thing_uuid": 999999999,
"discovery_timeout": 10,
"installation_timeout": 90,
"configuration_payload":
{
"title": "Some Title",
"url": "https://www.someurl.com/",
"category": "test",
"views": 9999
}
}
""".data(using: .utf8)!

let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
let registration = try! decoder.decode(Registration.self, from: jsonData)

let encoder = JSONEncoder()
encoder.keyEncodingStrategy = .convertToSnakeCase

let payloadString = String(data: try! encoder.encode(registration.configurationPayload), encoding: .utf8)!
print(payloadString) // {"title":"Some Title","views":9999,"url":"https:\/\/www.someurl.com\/","category":"test"}

The only problem I can see is potential loss of precision when decoding decimal numbers, which is a known problem with Foundation JSON decoder.
Also, some null values could be also removed. This could be fixed by decoding object manually by iterating keys and having a special null type.

Decode json array as an object in swift

First, I assume you'd really like the final result to be [Product] where Product looks like this:

struct Product {
var name: String = ""
var quantity: Int = 0
}

So if any keys are missing, they'll get the defaults. You could change this solution to throw an error in that case, but I think this approach is much nicer than Optionals.

Given that, here's how you decode it:

extension Product: Decodable {
init(from decoder: Decoder) throws {
// This is a very uniform type (all Strings). Swift can decode that
// without much help.
let container = try decoder
.singleValueContainer()
.decode([String: [[String: String]]].self)

// Extract the Products. Throwing an error here might be nicer.
let keyValues = container["Product"] ?? []

// This loops over every Key-Value element, and then loops through
// each one. We only expect one element in the second loop, though.
for keyValue in keyValues {
for (key, value) in keyValue {
switch key {
case "Name": self.name = value
case "Quantity": self.quantity = Int(value) ?? 0
default: break // Ignore unknown keys
}
}
}
// This solution just assigns defaults for missing keys, but
// you could validate that everything was found, and throw an
// error here if desired.
}
}

let data = try JSONDecoder().decode([Product].self, from: jsonData)
// [{name "exampleName", quantity 1}]

data.first!.name
// "exampleName"

In most cases the above is probably fine, but it's also very sloppy about malformed data. It just returns a default object, which could make an error very hard to track down. This example goes in the other direction, and does all the error checking you would expect from a normal Decodable.

First, we'll need a CodingKey that can accept any String. I really don't understand why this isn't built into stdlib:

struct AnyStringKey: CodingKey, Hashable, ExpressibleByStringLiteral {
var stringValue: String
init(stringValue: String) { self.stringValue = stringValue }
init(_ stringValue: String) { self.init(stringValue: stringValue) }
var intValue: Int?
init?(intValue: Int) { return nil }
init(stringLiteral value: String) { self.init(value) }
}

I also find DecodingErrors very cumbersome to build, so I often build little helper functions:

func keyNotFound(_ key: String, codingPath: [CodingKey]) -> Error {
DecodingError.keyNotFound(AnyStringKey(key),
.init(codingPath: [],
debugDescription: "\(key) key not found"))
}

func typeMismatch(_ key: String, expected: Any.Type, codingPath: [CodingKey]) -> Error {
DecodingError.typeMismatch(expected, .init(codingPath: codingPath + [AnyStringKey(key)],
debugDescription: "Expected \(expected)."))
}

With those in place, here's a more strict decoder:

extension Product: Decodable {
init(from decoder: Decoder) throws {
// This is a very uniform type (all Strings). Swift can decode that
// without much help.
let container = try decoder
.singleValueContainer()
.decode([String: [[String: String]]].self)

var codingPath: [AnyStringKey] = []

// Extract the Products. Throwing an error here might be nicer.
guard let keyValues = container["Product"] else {
throw keyNotFound("Product", codingPath: codingPath)
}

codingPath.append("Product")

var name: String?
var quantity: Int?

// This loops over every Key-Value element, and then loops through
// each one. We only expect one element in the second loop, though.
for keyValue in keyValues {
for (key, value) in keyValue {
switch key {
case "Name":
name = value

case "Quantity":
guard let intValue = Int(value) else {
throw typeMismatch("Quantity",
expected: Int.self,
codingPath: codingPath)
}
quantity = intValue

default: break // Ignore unknown keys
}
}
}

guard let name = name else {
throw keyNotFound("Name", codingPath: codingPath)
}
self.name = name

guard let quantity = quantity else {
throw keyNotFound("Quantity", codingPath: codingPath)
}
self.quantity = quantity
}
}


Related Topics



Leave a reply



Submit