Convert JSON string to HashMap in Java - json

How can I convert JSON string to HashMap. My JSON string is like
{
"AvailableDeliveries": {
"500": {
"code": "INOFFICE",
"desc": "In Office",
"id": 500,
"name": "IN OFFICE"
},
"502": {
"code": "TELEPHONE",
"desc": "Telephone",
"id": 502,
"name": "TELEPHONE"
},
"503": {
"code": "DIY DOC ACCESS",
"desc": "Online Documents",
"id": 503,
"name": "DIY DOC ACCESS"
}
}
}
I looked on other examples which have collection of object but I have this extra top level object "AvailableDeliveries" not sure how to handle that level.

import jackson-all-1.8.2.jar
create a mapper for the object mapper
ObjectMapper objectMapper = new ObjectMapper();
create a hashmap
map = objectMapper.readValue( json, HashMap.class );
Hope this will work

Related

How to get particular value from JSON object in flutter?

I wanted to get value from the API JSON object. My API JSON response is like this.
{
"jobs": [
{
"id": 1,
"user_id": "10",
"job_id": "1",
"experience": "12",
"salary": "1122378"
"job": {
"id": 1,
"title": "PHP SENIOR DEVELOPER",
"company_name": "Envato",
}
}
]
}
I wanted to get the title from the job JSON object. How can we get this value in flutter?
String jobTitle = json['jobs'][0]['job']['title'];
You can achieve this by doing the followng
final Map<String, dynamic> response = {
"jobs": [
{
"id": 1,
"user_id": "10",
"job_id": "1",
"experience": "12",
"salary": "1122378",
"job": {
"id": 1,
"title": "PHP SENIOR DEVELOPER",
"company_name": "Envato",
}
}
],
};
final List<Map<String, dynamic>> jobs = response['jobs'];
final Map<String, dynamic> job = jobs.first['job'];
final String jobTitle = job['title'];
print(jobTitle);
if you get title of the job inside jobs section try below code :
var response = jsonDecode(response.body);
var title = response['jobs'][0]['job']['title'];
You can use https://app.quicktype.io/ to generate the deserialization, so you can handle it by models to prevent errors.
Check: https://flutter.dev/docs/development/data-and-backend/json

How do I load a JSON file into the DOM in Saxon running in Java?

In my Java code I am trying to create a Saxon document (DOM) that is the contents of a JSON file. This should be possible but the code I have fails.
The full code for this is at SaxonQuestions.zip, TestLoadJson.java and is also listed below. In this code the evaluate() fails.
TestLoadJson.java
import net.sf.saxon.Configuration;
import net.sf.saxon.s9api.*;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;
import javax.xml.transform.sax.SAXSource;
import java.io.*;
import java.nio.charset.Charset;
public class TestLoadJson {
public static void main(String[] args) throws Exception {
// get the file
File jsonFile = new File("files", "SouthWind.json");
Charset inputCharset = Charset.forName("UTF-8");
FileInputStream fis = new FileInputStream(jsonFile);
InputStreamReader isr = new InputStreamReader(fis, inputCharset);
BufferedReader br = new BufferedReader(isr);
String str;
StringBuilder buf = new StringBuilder();
while ((str = br.readLine()) != null)
buf.append(str).append('\n');
br.close();
isr.close();
fis.close();
// set up the compiler
Configuration config = XmlDatasource.createEnterpriseConfiguration();
Processor processor = new Processor(config);
XPathCompiler xPathCompiler = processor.newXPathCompiler();
// need an XML document
DocumentBuilder doc_builder = processor.newDocumentBuilder();
XMLReader reader = XmlDatasource.createXMLReader();
InputSource xmlSource = new InputSource(new ByteArrayInputStream("<root/>".getBytes()));
SAXSource saxSource = new SAXSource(reader, xmlSource);
XdmNode xmlRootNode = doc_builder.build(saxSource);
// give it the JSON
buf.insert(0, "parse-json(");
buf.append(")");
Object json = xPathCompiler.evaluate(buf.toString(), xmlRootNode);
System.out.println("JSON read in!!! json = " + json);
}
}
If you have a Java String with JSON pass it in as a variable to XPath and call parse-json on the variable:
Processor processor = new Processor(true);
String[] jsonExamples = { "1", "true", "null", "\"string\"", "[1,2,3]", "{ \"prop\" : \"value\" }" };
XPathCompiler compiler = processor.newXPathCompiler();
compiler.declareVariable(new QName("json"));
XPathExecutable executable = compiler.compile("parse-json($json)");
XPathSelector selector = executable.load();
for (String json : jsonExamples) {
selector.setVariable(new QName("json"), new XdmAtomicValue(json));
XdmValue value = selector.evaluate();
System.out.println(value);
}
If you have a file with JSON pass its file name or in general URI as a variable to XPath and call json-doc (https://www.w3.org/TR/xpath-functions/#func-json-doc) on the variable:
compiler = processor.newXPathCompiler();
compiler.declareVariable(new QName("json-uri"));
executable = compiler.compile("json-doc($json-uri)");
selector = executable.load();
selector.setVariable(new QName("json-uri"), new XdmAtomicValue("example1.json")); // pass in a relative (e.g. 'example.json' or 'subdir/example.json') or an absolute URI (e.g. 'file:///C:/dir/subdir/example.json' or 'http://example.com/example.json') here, not an OS specific file path
XdmValue value = selector.evaluate();
System.out.println(value);
Of course you can separate the steps and parse a string to an XdmValue or a file to an XdmValue and then pass it in later as a variable to another XPath evaluation.
So lets assume you have employees.json containing
{
"employees": [
{
"name": "mike",
"department": "accounting",
"age": 34
},
{
"name": "sally",
"department": "sales",
"age": 24
}
]
}
then you can parse it with the second sample into an XdmValue value and use that further as a context item for an expression e.g
avg(?employees?*?age)
would compute the average age:
Processor processor = new Processor(true);
XPathCompiler compiler = processor.newXPathCompiler();
compiler.declareVariable(new QName("json-uri"));
XPathExecutable executable = compiler.compile("json-doc($json-uri)");
XPathSelector selector = executable.load();
selector.setVariable(new QName("json-uri"), new XdmAtomicValue("employees.json"));
XdmValue value = selector.evaluate();
System.out.println(value);
executable = compiler.compile("avg(?employees?*?age)");
selector = executable.load();
selector.setContextItem((XdmItem) value);
XdmItem result = selector.evaluateSingle();
System.out.println(result);
At https://xqueryfiddle.liberty-development.net/94hwphZ I have another sample processing JSON, it also computes the average of a value with an expression using the lookup operator ?, first with ?Students to select the Students item of the context map, then with an asterisk ?* on the returned array to get a sequence of all array items, finally with ?Grade to select the Grade value of each array item:
avg(?Students?*!(?Grade, 70)[1])
but with the additional requirement to select a default of 70 for those objects/maps that don't have a Grade. The sample JSON is
{
"Class Name": "Science",
"Teacher\u0027s Name": "Jane",
"Semester": "2019-01-01",
"Students": [
{
"Name": "John",
"Grade": 94.3
},
{
"Name": "James",
"Grade": 81.0
},
{
"Name": "Julia",
"Grade": 91.9
},
{
"Name": "Jessica",
"Grade": 72.4
},
{
"Name": "Johnathan"
}
],
"Final": true
}
The fiddle supports XQuery 3.1 but like for XPath 3.1 the JSON is passed in as a variable and then parsed with parse-json into an XDM item to serve as the context item for further evaluation.
To give some examples of more complex XPath 3.1 expressions against JSON I have taken the JSON sample from the path examples in https://github.com/json-path/JsonPath as the JSON input to parse-json (if you have a string) or json-doc if you have a URI to a file or even a HTTP(S) location and used it as the context item for some paths (evaluated in the fiddle as XQuery 3.1 but XPath 3.1 is a subset and I think I have restricted the samples to XPath 3.1:
The samples are at:
https://xqueryfiddle.liberty-development.net/gWmuPs6/0 : ?store?book?*?author : "the authors of all books"
https://xqueryfiddle.liberty-development.net/gWmuPs6/1 : ?store?* : "all things in the store, both books and bicycles"
https://xqueryfiddle.liberty-development.net/gWmuPs6/2 : ?store?book?3 : "the third book"
https://xqueryfiddle.liberty-development.net/gWmuPs6/3 : ?store?book?(1,2) : "the first two books"
https://xqueryfiddle.liberty-development.net/gWmuPs6/4 : ?store?book?*[?isbn] : "all books with an isbn number"
https://xqueryfiddle.liberty-development.net/gWmuPs6/5 : ?store?book?*[?price < 10] : "all books with a price less than 10"
https://xqueryfiddle.liberty-development.net/gWmuPs6/6 : let $context := . return ?store?book?*[?price <= $context?expensive] : "all books with a price less than expensive"
https://xqueryfiddle.liberty-development.net/gWmuPs6/7 : count(?store?book?*) : "the number of books"
The file is
{
"store": {
"book": [
{
"category": "reference",
"author": "Nigel Rees",
"title": "Sayings of the Century",
"price": 8.95
},
{
"category": "fiction",
"author": "Evelyn Waugh",
"title": "Sword of Honour",
"price": 12.99
},
{
"category": "fiction",
"author": "Herman Melville",
"title": "Moby Dick",
"isbn": "0-553-21311-3",
"price": 8.99
},
{
"category": "fiction",
"author": "J. R. R. Tolkien",
"title": "The Lord of the Rings",
"isbn": "0-395-19395-8",
"price": 22.99
}
],
"bicycle": {
"color": "red",
"price": 19.95
}
},
"expensive": 10
}

What is wrong with this JSON file? Can't be deserialized

I have an issue with a JSON file, which is a list of country objects, as below:
{
"Countries": [
{
"Code": "AFG",
"Name": "Afghanistan",
"Population": 38928346
},
{
"Code": "ALA",
"Name": "Åland Islands",
"Population": 28007
},
{
"Code": "ALB",
"Name": "Albania",
"Population": 2877797
},
{
"Code": "DZA",
"Name": "Algeria",
"Population": 43851044
},
{
"Code": "ASM",
"Name": "American Samoa",
"Population": 55191
}
]
}
I am trying to use this code to read it and deserialize it into a List object:
Stream? countriesResourceStream = Assembly.GetExecutingAssembly().GetManifestResourceStream("MyProject.Countries.json");
if (countriesResourceStream == null)
{
return;
}
var countries = new List<Country>();
using (StreamReader reader = new StreamReader(countriesResourceStream))
{
var serializer = new JsonSerializer();
countries = serializer.Deserialize<List<Country>>(new JsonTextReader(reader));
}
However the serializer.Deserialize method throws the exception:
'Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[MyProject.Models.EntityFramework.Country]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object.
What is the issue with my JSON? I have tried both Newtonsoft and System.Text.Json.
The problem is that your JSON does not represent a list of countries, it represents an object that contains a list of countries. You need another class:
class CountryListContainer
{
public List<Country> Countries { get; set; }
}
Deserialize into the container class and then you can get your country list from that:
using (StreamReader streamReader = new StreamReader(countriesResourceStream))
using (JsonTextReader jsonReader = new JsonTextReader(streamReader))
{
var serializer = new JsonSerializer();
countries = serializer.Deserialize<CountryListContainer>(jsonReader).Countries;
}
Fiddle: https://dotnetfiddle.net/5DM4il
Alternatively, you could change your JSON as #Charles Duffy suggested in the comments. If the JSON looked like this (without the outer object) then your existing code would work:
[
{
"Code": "AFG",
"Name": "Afghanistan",
"Population": 38928346
},
{
"Code": "ALA",
"Name": "Åland Islands",
"Population": 28007
},
{
"Code": "ALB",
"Name": "Albania",
"Population": 2877797
},
{
"Code": "DZA",
"Name": "Algeria",
"Population": 43851044
},
{
"Code": "ASM",
"Name": "American Samoa",
"Population": 55191
}
]
Fiddle: https://dotnetfiddle.net/gMHhcX

jdbcTemplate - Convert data from JSON column

Tools: Spring Booot v2.1.3.RELEASE, MySQL 5.7
I have table with column of type JSON named "properties".
I use jdbcTemplate.queryForList(sql) method to read from this table.
Rest service returns something like this:
[
{
"id": 1,
"name": "users",
"properties": "{\"prop1\": \"value1\"}",
"description": "smpl descr1",
"log_enabled": false
},
{
"id": 2,
"name": "members",
"properties": null,
"description": "sample description 2",
"log_enabled": true
}
]
As you can see the "properties" object is type of String.
How to force jdbcTemplete to convert data from JSON column into JSON instead of String?
Expected result:
[
{
"id": 1,
"name": "users",
"properties": {
"prop1": "value1"
},
"description": "smpl descr1",
"log_enabled": false
},
{
"id": 2,
"name": "members",
"properties": null,
"description": "sample description 2",
"log_enabled": true
}
]
I am sorry that JdbcTemplete does not have such function. You have to convert the JSON string to the java object by yourself using your favourite JSON library.
For example , in case of Jackson , you can convert any JSON string to a Map using:
ObjectMapper mapper = new ObjectMapper();
String json = "{\"prop1\": \"value1\" , \"prop2\": 123}";
Map<String,Object> result = mapper.readValue(json,new TypeReference<Map<String,Object>>() {});
result.get("prop1") // "value1"
result.get("prop2") // 123

How to pass a JSON file from the back-end to the front-end

I have a JSON file with a list of products in my back-end ( Spring ). I want to be able to pass the content to the front-end ( in Angular ).
I have a JSON file in an assets folder in my front-end made with angular.
This is the JSON file:
[ {
"brand": "",
"category": {
"id": 29,
"name": "hand held"
},
"description": "New D131 Scanner complete",
"hidden": false,
"id": 10,
"image": null,
"productNumber": "E14NO1617",
"quantity":1
},
{
"brand": "",
"category": {
"id": 29,
"name": "hand held"
},
"description": "New D132 Scanner complete",
"hidden": false,
"id": 10,
"image": null,
"productNumber": "E14NO1617",
"quantity":1
},
{
"brand": "",
"category": {
"id": 50,
"name": "card reader"
},
"description": "USB,
"hidden": false,
"id": 26,
"image": null,
"productNumber": "ST-1044UB",
"quantity": 1
}
]
I then display the objects ( products in my case ) on a table with the following function in the service:
getTemplates() : Promise<Product[]> {
return this.http.get<Product[]>("http://localhost:4200/assets/BirdyProducts.json")
.toPromise();
}
This works exactly like I want it to be displayed,
But I don't want to store the the JSON in my front-end assets folder.
I want it to be in my back-end in a resources folder and send the file with a rest-controller and still get the same result.
I tried a lot with Objectmapper, JSONObjects,... but did not find a solution.
#Controller
public class BirdyProductsController {
#RequestMapping(
value = "/birdyProducts",
method = RequestMethod.GET,
produces = MediaType.APPLICATION_JSON_VALUE
)
String getBirdyProducts() {
return "json/BirdyProducts.json";
}
}
This worked for me.
Path to JSON file: \src\main\resources\static\json\BirdyProducts.json
#RestController
#RequestMapping
public class ExampleController {
#GetMapping("/BirdyProducts")
public InputStreamResource getJsonFile() throws IOException {
return new InputStreamResource(new ClassPathResource("/assets/BirdyProducts.json").getInputStream());
}
}
When I request for http://localhost:8080/BirdyProducts I get the content of the file.
The file is in the \src\main\resources\assets folder on the backend side.