I want to parse a json response like that :
{
"code": "#546545"
}
from an angular 2 service. There are two ways that I know of:
Use an interface
export interface ProductId{
code: string;
}
Since json is a string use: angular.fromJson(code)
I think 1 is an overkill for a single string along with what I know what is the best way for something so simple?
Either JSON.parse(string) or
angular.fromJson(string)
which is just
function fromJson(json) {
return isString(json)
? JSON.parse(json)
: json;
}
The interface would help you, I don't think it's an overkill. But you still need to parse the string anyway.
Related
I would like to add linebreakers to a JSON string so it will be more readable.
val myString = "some string"
val myObjectJson = `
{
"example1": "value",
"example2": $myString
}`
So later I can use ObjectMapper to create an object. objectMapper.readValue(myObjectJson, MyClass::class.Java)
What I'm trying to figure out:
How to add lineBreaker in Json string?
Tried template literals:"`", doesn't seem to work in Kotline. gives Expecting an expression error.
How to use variable in Json string?
This might go away after I figure out how to add linebreakers.
(Edited because I think I have misunderstood your question).
Are you asking how to lay out a JSON string in the source code? If so then what you are looking for is the Raw String feature implemented with 3 double-quotes like this:
val myObjectJson = """
{
"example1": "value",
"example2": $myString
}
"""
But in case you asking
How to add lineBreaker in Json string?
(Assuming you are using Jackson's ObjectMapper)
Simply use writerWithDefaultPrettyPrinter() like this: MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(value)
If that is not good enough for you I suppose you could implement a custom Pretty Printer: https://www.javadoc.io/static/com.fasterxml.jackson.core/jackson-core/2.14.2/com/fasterxml/jackson/core/PrettyPrinter.html
So i'm just starting out with typescript and something that I can't find much info on is how to deal with types for api call responses.
Lets say, I make a GET request to an api and it returns a JSON object for example:
{
name: "john",
age: 12
}
in my code, if i wanted to interact with response.name would i have to create an interface like below to use response.name without having a red linter under it?
interface Response {
name: string,
age: number
}
or is there a easier way to do it as some api calls would return JSON > 10 lines long and copying out the whole structure for every type of call seems very troublesome. Another thought I had was to create the interface but only have values I would use instead of the whole structure, but i'm not too sure so any help would be greatly appreciated!
You can define Response as a "common" type, that supports all types of API json response.
interface IResponse {
[key: string]: any
}
Now, you can type response.name without the "red line", also response.not_exist_property is valid.
My recommendation is to define all types for all API response type:
interface GetUserResponse {
name: string,
age: number,
}
for GET /users/:id (example)
You can use this tool to convert a json response to Typescript type.
I'm calling a REST service using Refit and I want to deserialize the JSON that is returned as a dynamic type.
I tried defining the interface as
[Get("/foo")]
Task<dynamic> GetFoo();
but the call times out.
I know I can deserialize to a dynamic like this
var mockString = "{ title: { name: 'fred', book: 'job'} }";
dynamic d = JsonConvert.DeserializeObject(mockString);
but I can't figure out what to pass to Refit to get it to do the same.
Another option would be to get Refit to pass the raw JSON back so I can deserialize it myself but I can't see a way to do that either.
Any ideas?
You can define your interface to return a string and get the raw JSON that way:
[Get("/foo")]
Task<string> GetFoo();
As described here:
https://github.com/paulcbetts/refit#retrieving-the-response
Refit uses JSON.NET under the hood, so any deserialization that works with that will work with Refit, including dynamic. The interface you have described is exactly right.
Here's a real working example:
public interface IHttpBinApi
{
[Get("/ip")]
Task<dynamic> GetIp();
}
var value = await RestService.For<IHttpBinApi>("http://httpbin.org").GetIp();
If you are using iOS and Refit 4+, you might be seeing this bug: https://github.com/paulcbetts/refit/issues/359
As Steven Thewissen has stated, you can use Task<string> as your return type (or Task<HttpResponseMessage>, or even Task<HttpContent>) to receive the raw response and deserialize yourself, but you shouldn't have to -- the whole point of Refit is that it's supposed to save you that hassle.
I come from a Python Background and recently started programming using TypeScript and Angular2. I want to know how to obtain keys from a JSON object using TypeScript.
I have a response like so:
response.text()
I pass this object to a function
removeMetaData (my_data: string){
//(Various manipulation)...etc
}
i have read that I can call a json() method instead of text(). If I do that, what is the type I should use for my_data?
Then,
If my JSON looks like this:
{
"count": 100,
"next_page": "http://www.test.com/users/?page=2",
"prev_page": "http://www.test.com/users/?page=3",
"results":[
{
"username": "johnny"
},
Etc....
]
How do I parse that?
I've read I might have to use an interface but I don't understand how.
In python it's just response["next_page"] to get the key of a dictionary, then I can assign that value to a variable within the class. That is exactly what I'm trying to achieve within a component.
Thank you.
ADDITION
list() {
this.requestService.get(this.api_path)
.subscribe(
response => this.populate(response.json()),
error => this.response = error.text()
)
}
populate(payload: object) {
this.count = payload.count;
this.next = payload.next;
this.previous = payload.previous;
*payload.results => this.users = payload.results;******
}
Declare an interface which will be used as value object.
export interface IPage
{
count:number;
next_page:string;
prev_page:string;
results:Array<any>;
...
...
}
var my_data:IPage;
Now assign parsed json value to my_data and access all the properties with '.' operator i.e. my_data.count, my_data.results.
Feel free to throw any question.
If I do that, what is the type I should use for my_data?
Its just a javascript object.
As an example if you json looks like:
{
"foo": {
"bar": "bas"
}
}
Then in the parsed json (in variable someObj) the value someObj.foo.bar would be bas 🌹
I have been trying to evaluate GWT Autobean feature to decode/encode JSON object to domain objects for REST calls.
Following the example : http://code.google.com/p/google-web-toolkit/wiki/AutoBean#Quickstart
I was able to convert a singular JSON object to a domain object:
AutoBean<Person> personBean = AutoBeanCodex.decode(factory, Person.class, JsonResources.INSTANCE.json().getText());
where JsonResources.INSTANCE.json() is returning a JSON string.
However, I haven't been successful to convert a list of Person objects from JSON.
It would be helpful, if anyone has an example of this?
Thanks!
Well the only way I can think of is to create a special autobean, which will have List<Person> property. For example:
public interface Result {
void setPersons(List<Person> persons);
List<Person> getPersons();
}
And example json string:
{
persons:[
{"name":"Thomas Broyer"},
{"name":"Colin Alworth"}
]
}
UPDATE:
Workaround when input JSON is an array ( as suggested by persons[0] in comments).E.g. JSON looks like this:
[{"name":"Thomas Broyer"},{"name":"Colin Alworth"}]
And parsing code looks like this:
AutoBeanCodex.decode(factory, Result.class, "{\"persons\": " + json + "}").getPersons();