I am a new guy for JSON, I don't know to send JSON object and Array...
But, I pass the JSON values like the below format,
object.put("code", "1");
object.put("message", "Success");
object.put("Name", "xxx");
object.put("F_Name","yyy");
object.put("Address", "zzz");
object.put("Phone_No","123");
out.println(object);
But it display like
{"Phone_No":"123","message":"Success","Address":"zzz","Name":"xxx","F_Name":"yyy","code":"1"}
I don't know, why it's display like this. How to order this? Please help me.
And this is what format, Array format or object format...
And tell how to send array values in JSON..
Thanks in advance..
You didn't write what is the class of the object. However, if you care about the order, use GSON and its JsonObject class:
import com.google.gson.Gson;
import com.google.gson.JsonObject;
JsonObject object = new JsonObject();
object.addProperty("code", "1");
object.addProperty("message", "success");
object.addProperty("Name", "xxx");
// ...
Gson gson = new Gson();
out.println(gson.toJson(object));
As my understanding of question and the code above, The "object" you already using might be json object. Usually JSON object can maintain data in the form of key, value pairs. So you are putting content into json object and displaying. That's why its getting displayed like that. The displayed format is json format. If you want to put array into json object you can put as you already did for normal strings.
object.put("array1", arrayvariable1[]);
object.put("array2", arrayvariable2[]);
I guess it might have helped you.
Related
I have a complex Kotlin data class, say something like this:
data class Post(
val message: Message,
val dateAndTime: LocalTime,
val postAuthor: Author?,
val visitorsVisitedTimes: List<Pair<LocalTime, Author>>
)
and each of Message, LocalTime, ... are different data classes.
I have an object of above Post data class. I want to parse it, access visitorsVisitedTimes field value, for each pair, replace Author object with corresponding postAuthor. I have to make similar changes in the Message object as well.
And I don't want to make changes in the class definition.
One way would be to convert this object into a json string, parse it, make require changes and cast it back to Post::class.java and return it.
I did something like this:
// input is an object of Post::class
var jsonString: String = Gson().toJson(input)
// parse the json string, make required changes
var objectFromJson: Post = Gson().fromJson(jsonString, Post::class.java)
return objectFromJson
But, I'm not sure how to make required changes in the Json string.
How can I do that, if not, is there any other way to do the task?
Create a copy of an object, see https://kotlinlang.org/docs/data-classes.html.
val newPost = post.copy(
message = post.message.copy(text = "some text"),
postAuthor = Author(...)
)
lets say I have a json array called arr, which contains some number of json objects, jsobj1, jsboj2,... jsbojn. if I want to add a new json object jsobjm inside of jsobj2 how would I do that?
I tried to do arr.get(1).put("jsobjm", jsobjm), but I get the error cannot find symbol, pointing to the . before the put().
Well you could do this (instead of manipulating the array as a String):
Convert the JSON array into it's object equivalent and add the object you want using the programming language you use.
Convert the object back to JSON
eg using Javascript
let arr = '[{\"name\":\"Ford\"}]';
//convert to object
let objArray = JSON.parse(arr);
let obj = objArray[0];
//add the other object you want into the first object
obj.description = {"reason":"My fav car"};
console.log(obj);
//convert everything back to string
console.log(JSON.stringify(obj));
JSfiddle: https://jsfiddle.net/allkenang/tuvxrgj3/8/
I haven't written any code yet but I have a JSON which I want to get a specific block of data from to display on a very rudimentary view. I just want to grad a block of data that is nested in a JSON. Is there method for doing such a thing simply with swiftui? Im a beginner at Swiftui.
Decoding/getting the data
There are multiple ways to access specific blocks of data from JSON data.
If you fetch your JSON object from an API, you'll likely need to decode it (Data type to custom type).
First method: using SwiftyJSON
There is a great library to access specific parts of a JSON object which is called SwiftyJSON.
They provide a few examples like this one:
let json = JSON(data: dataFromNetworking)
if let userName = json[0]["user"]["name"].string {
//Now you got your value
}
Second method: using pure Swift
You have to serialize your JSON object and afterwards, you can access a specific block using:
if let statusesArray = try? JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [[String: Any]],
let user = statusesArray[0]["user"] as? [String: Any],
let username = user["name"] as? String {
// Finally we got the username
}
Third method: using custom Structs and Enums
The last method is to create a data model and parse your JSON. To create your data model you can use an app called quicktype.
You can then decode simply. Here's a link to show you how.
Using/displaying the data
After decoding the data, you can parse it to an ObservableObject and loop through it using a List or a ForEach.
I am making a audio player using
<audio src={audioSrc}>
tag.
When I get the audio file, it was a binary file(blob below) so I created a blob with it.
let test = new Blob(blob, {type: 'audio/mp3'};
And then created an object url
let objUrl = URL.createObjectURL(test);
This objUrl looks like blob:https://xxxxx and when I pass this string to <audio src={objUrl}/>, I cannot hear anything.
I was wondering if I have to convert this url to make it available in audio tag.
Can I get an advice for this problem please?
The first parameter of the Blob constructor is an array. MDN describes it like this:
An Array of ArrayBuffer, ArrayBufferView, Blob, USVString objects, or a mix of any of such objects, that will be put inside the Blob. USVString objects are encoded as UTF-8.
https://developer.mozilla.org/en-US/docs/Web/API/Blob/Blob#parameters
Maybe creating your blob like this already solves the problem:
let test = new Blob([ blob ], { type: 'audio/mp3' });
Another problem I could think of is that the binary data has a different mimeType other than 'audio/mp3' which could cause the audio element to give up decoding the data.
Just add another prop autoplay
<audio src={URL.createObjectURL(test)} autoplay/>
json image
i am trying to get json object value but did not get
json = JSON.parse(json);
alert(json.observations[0].dateCorrect);
Your json is probably wrongly encoded. The actual key is "observations[0].dateCorrect". See matching quotes:
So you'll have to do json['observations[0].dateCorrect'] to get what you want, but you better (if you can) change how json is encoded first.
To make it clearer:
var data = JSON.parse(json);
var key = 'observations[0].dateCorrect';
alert(data[key]);
that's coz the thats not JSON, this is a string you need to parse it before accessing it.
try this
var obj = JSON.parse(json);
alert(obj.observations[0].dateCorrect);