Deserializing Json Object in java [duplicate] - javascript

This question already has answers here:
How to parse JSON in Java
(36 answers)
Closed 6 years ago.
I cannot figure it out, I should deserialize a json object of this type:
{
"value":integer",
"total":1",
"records":138",
"rows":[
{
"value1":6,
"value2":true,
"bool":true,
"floatNumber":140.41",
"floatNumber2":28.7",
"floatNumber3":140.41",
"cssClassName":""",
"date":"19/03/2022"",
"UTCdate":"2016-03-22T00:00:00+0000"",
"UTCdate2":"2016-03-24T20:45:25+0000"
},
{
"value1":6,
"value2":true,
"bool":true,
"floatNumber":140.41",
"floatNumber2":28.7",
"floatNumber3":140.41",
"cssClassName":""",
"date":"19/03/2022"",
"UTCdate":"2016-03-22T00:00:00+0000"",
"UTCdate2":"2016-03-24T20:45:25+0000"}
]}
but I do not know how to do. I wish that this item was added to my class, pointing to what value to assign the corresponding property.
I tried to use Flexjson library but didn't saw any function that will let me what i want to do.
Where to start?
PS: I never serialized an object to JSON, so I do not know how it works.

You can go through this tutorial. Hope it will help you.
How to convert Java object to / from JSON (Jackson)
https://dzone.com/articles/deserializing-json-java-object

That's json. You need to parse it using api.
For example
{'profiles': [{'name':'john', 'age': 44}, {'name':'Alex','age':11}]}
you will have to do something of this effect:
JSONObject myjson = new JSONObject(the_json);
JSONArray the_json_array = myjson.getJSONArray("profiles");
this returns the array object.
Then iterating will be as follows:
int size = the_json_array.length();
ArrayList<JSONObject> arrays = new ArrayList<JSONObject>();
for (int i = 0; i < size; i++) {
JSONObject another_json_object = the_json_array.getJSONObject(i);
//Blah blah blah...
arrays.add(another_json_object);
}
//Finally
JSONObject[] jsons = new JSONObject[arrays.size()];
arrays.toArray(jsons);
Example code is taken from How to parse a JSON and turn its values into an Array?

Java or Javascript? You do know that these are 2 completely different languages?
In Javascript you do it like this:
// object to string:
JSON.stringify(object);
// string to object
JSON.parse(object);

Related

How to parsing the correct values from a json decoding [duplicate]

This question already has an answer here:
PHP or JavaScript issue when parsing JSON encoded PHP array into JavaScripts JSON.parse()
(1 answer)
Closed 1 year ago.
Hii ha ve written this question because i have a json converted to a string with a function of php called json_encode()
Something like this:
{ "data":"2","state":"false"}
when the original json that im trying to encode is like this:
{ "data":2,"state":false}
(Please note that the type of the variables are different, in the original i have an int number called data and boolean called state, but when i use json_encode() every variable goes to a string..)
The problem is when i try to json.PARSE() the value from the json encode of php in angular i don´t get the correct value, every variable is a string...
For example, isntead of getting the boolean state of the variable, i get "false" or "true", and this is a problem...
There is a way to parse this avoiding this problem? basically my problem is when i parse the json in my angular project i dont get the correct type of variable..
Thanks!
You can use JSON.parse on an individual value to convert it into the desired type:
const oldValue = JSON.parse('{"data":"2","state":"false"}')
const result = {}
Object.keys(oldValue).forEach(key => {
result[key] = JSON.parse(oldValue[key]);
});
Here's the other way around:
const oldValue = JSON.parse('{"data": 2,"state": false}');
const result = {}
Object.keys(oldValue).forEach(key => {
result[key] = oldValue[key].toString();
});
Note: These examples assume flat objects. You'd need to recurse through the object's tree if some of the values are objects, for example {a: {b: "c"}}.

How to convert string into array of object? [duplicate]

This question already has answers here:
Best way to convert string to array of object in javascript?
(7 answers)
Closed 4 years ago.
let str="{SPOT:0,0:10,1:0},{SPOT:1,0:5,1:5}";
let result=[{"SPOT":0,"0":10,"1":0},{"SPOT":1,"0":5,"1":5}];
How to convert string to array of object
We can make it look like an array using template literals and a little bit of replace.
When it looks right we can use JSON.parse to actually turn it into an array
Now we have an array we can use forEach to go through each string and make them look like objects, we'll use replace again.
Once we've made each string look like an object we can push them into an empty results array, we'll have to make one outside of the loop.
Putting all this together looks a little like this:
const str = "{SPOT:0,0:10,1:0},{SPOT:1,0:5,1:5}";
let result = [];
JSON.parse(`["${str}"]`.replace(/},{/g, `}","{`)).forEach((e) => {
result.push(JSON.parse(e.replace(/{/g, `{"`).replace(/:/g, `":`).replace(/,/g, `,"`)));
});
console.log(result)
I hope you find this helpful.
Well this is not the best approach I would say but still, it will solve your problem:
let str = "{SPOT:0,0:10,1:0},{SPOT:1,0:5,1:5}";
let newStr = str.replace("},{", "}TempString{"); //append any dummy string in the existing one
let result = newStr.split("TempString");
console.log(result)

javascript- How to parse JSON using javascript [duplicate]

This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 5 years ago.
If my json is this:
[
["cat1"],
["cat2"],
["cat3"],
["cat4"],
["cat5"]
]
How to parse this in javascript. I am looking for some for loop kind of solution which can iterate over the json and can give me "cat1 ", "cat2" etc.
P.S.: My json list is dynamic which i am getting from some source. So, i dont know how my json elements are there and what are the fields.
Most browsers support JSON.parse(), which is defined in ECMA-262 5th Edition (the specification that JS is based on). Its usage is simple:
var json = '{"result":true,"count":1}',
obj = JSON.parse(json);
alert(obj.count);
For the browsers that don't you can implement it using json2.js.
As noted in the comments, if you're already using jQuery, there is a $.parseJSON function that maps to JSON.parse if available or a form of eval in older browsers. However, this performs additional, unnecessary checks that are also performed by JSON.parse, so for the best all round performance I'd recommend using it like so:
var json = '{"result":true,"count":1}',
obj = JSON && JSON.parse(json) || $.parseJSON(json);
This will ensure you use native JSON.parse immediately, rather than having jQuery perform sanity checks on the string before passing it to the native parsing function.
try this.
var list= [
["cat1"],
["cat2"],
["cat3"],
["cat4"],
["cat5"]
];
list.forEach(function(item){
console.log(item[0]);
});

Accessing an object from a JSON array of objects yields "Undefined" [duplicate]

This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 6 years ago.
I'm using a Blockspring API that returns a JSON array of objects (read in from a Google Sheet). However, whenever I try to access an object from the array, an "undefined" value is returned. I have attached the code and the console log below. Does anyone have any ideas why?
blockspring.runParsed("query-public-google-spreadsheet", { "query": "SELECT A, B, C", "url":
"https://docs.google.com/spreadsheets/d/1ZYvcYf_41aghdXRSpg25TKW4Qj9p1Lpz92b1xG-9R1Q/edit?usp=sharing"},
{ "api_key": "br_50064_1fe91fe1478ef990dc8b5e9b4041c2c476670306" }, function(res){
var obj=res.params;
console.log(obj);
var temp=obj[0];
console.log(temp);
}
You need to use obj.data[0] to access the first element of an array.
Looking at your output in the console, it seems you are missing the data property of obj.
Object obj doesn't have a property with name 0 so it returns undefined.
I would need to play around with it myself but I can tell that the problem is just how you are accessing the info.
When you try to grab the data with var temp=obj[0] you are treating object like an array when is it not. I would recommend trying to grab the data using this:
//get the actual array
JSONArray theArray = obj.getJSONArray("data"); //I believe it is stored in an array called data... could be that the obj is just fine
// now get the first element:
JSONObject firstItem = theArray.getJSONObject(0);
// and so on
String name = firstItem.getString("Name"); // A
You most likely can grab it using var temp = obj.data[0];

JSON using parse or stringify correctly [duplicate]

This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 8 years ago.
This is what I'm getting from server
['model':{"category":[{"id":1}],"food":[{"id":1}].... // long json here
How can I use jquery/javascript to parse to get category id and food id? I tried to use
JSON.parse(data)
or
JSON.stringify(data)
And after that, doing
$.each(data, function (i, x) {
it will give me each letter of all array. How can I parse it correctly, getting the ids that I want?
JSON.parse(data) will turn the data you showing into a JavaScript object, and there are a TON of ways to use the data from there. Example:
var parsedData = JSON.parse(data),
obj = {};
for(var key in parsedData['model']){
obj[key] = parsedData['model'][key]['id'];
}
Which would give you a resulting object of this:
{category:1, food:1}
This is based on the limited example of JSON you provided, the way you access it is entirely dependent on its structure. Hopefully this helps get you started, though.
You want to use JSON.parse(), but it returns the parsed object, so use it thusly:
var parsed = JSON.parse(data);
then work with parsed.

Categories

Resources