How to Decode This 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
)

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)

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.

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

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.

How can I decode in PHP a json string that has a json string as a value inside?

Based on provided input - you must replace all those nasty backslashes and double quotes in order to get proper JSON:

<?php
$s = '{
"key1": "value1",
"key2": "{\"key3\":\"{\\\"key4\\\":\\\"value4\\\"}\"}"
}';

$s = str_replace('\\', '', $s);
$s = str_replace('"{', '{', $s);
$s = str_replace('}"', '}', $s);

print_r(json_decode($s, true));
?>

Output:

Array
(
[key1] => value1
[key2] => Array
(
[key3] => Array
(
[key4] => value4
)
)
)


Related Topics



Leave a reply



Submit