我应该如何使用Node.js解析JSON?是否有一些模块可以安全地验证和解析JSON?
我最近使用TypeScript观看了Angular 2的教程,但不确定何时使用接口以及何时使用模型来保存数据结构.
界面示例:
export interface IProduct {
ProductNumber: number;
ProductName: string;
ProductDescription: string;
}
Run Code Online (Sandbox Code Playgroud)
型号示例:
export class Product {
constructor(
public ProductNumber: number,
public ProductName: string,
public ProductDescription: string
){}
}
Run Code Online (Sandbox Code Playgroud)
我想从URL加载JSON数据并绑定到接口/模型.有时我想要一个数据对象,其他时候我想要持有对象的数组.
我应该使用哪一个?为什么?
我知道如何解析JSON字符串并将其转换为JavaScript对象.您可以JSON.parse()在现代浏览器(和IE9 +)中使用.
这很好,但是如何将JavaScript对象转换为特定的 JavaScript对象(即使用某个原型)?
例如,假设你有:
function Foo()
{
this.a = 3;
this.b = 2;
this.test = function() {return this.a*this.b;};
}
var fooObj = new Foo();
alert(fooObj.test() ); //Prints 6
var fooJSON = JSON.parse({"a":4, "b": 3});
//Something to convert fooJSON into a Foo Object
//....... (this is what I am missing)
alert(fooJSON.test() ); //Prints 12
Run Code Online (Sandbox Code Playgroud)
同样,我不知道如何将JSON字符串转换为通用JavaScript对象.我想知道如何将JSON字符串转换为"Foo"对象.也就是说,我的对象现在应该有一个函数'test'和属性'a'和'b'.
更新 在做了一些研究后,我想到了......
Object.cast = function cast(rawObj, constructor)
{
var obj = new constructor();
for(var i in rawObj)
obj[i] = rawObj[i];
return obj; …Run Code Online (Sandbox Code Playgroud) 我做了很多研究,但我对我发现的东西并不完全满意.只是为了确定这是我的问题:什么是将JSON反序列化为TypeScript运行时类实例的最强大,最优雅的自动化解决方案?
说我上了这堂课:
class Foo {
name: string;
GetName(): string { return this.name };
}
Run Code Online (Sandbox Code Playgroud)
并说我有这个JSON字符串用于反序列化:
{"name": "John Doe"}
Run Code Online (Sandbox Code Playgroud)
获取名称设置为"John Doe"和GetName()方法的Foo类实例的最佳和最易维护的解决方案是什么?我非常具体地问,因为我知道很容易反序列化为纯数据对象.我想知道是否可以使用工作方法获取类实例,而无需进行任何手动解析或任何手动数据复制.如果无法实现全自动化解决方案,那么下一个最佳解决方案是什么?
我目前正在尝试将我收到的JSON对象转换为具有相同属性的TypeScript类,但我无法使其工作.我究竟做错了什么?
员工类
export class Employee{
firstname: string;
lastname: string;
birthdate: Date;
maxWorkHours: number;
department: string;
permissions: string;
typeOfEmployee: string;
note: string;
lastUpdate: Date;
}
Run Code Online (Sandbox Code Playgroud)
员工字符串
{
"department": "<anystring>",
"typeOfEmployee": "<anystring>",
"firstname": "<anystring>",
"lastname": "<anystring>",
"birthdate": "<anydate>",
"maxWorkHours": <anynumber>,
"username": "<anystring>",
"permissions": "<anystring>",
"lastUpdate": "<anydate>"
//I will add note later
}
Run Code Online (Sandbox Code Playgroud)
我的尝试
let e: Employee = new Employee();
Object.assign(e, {
"department": "<anystring>",
"typeOfEmployee": "<anystring>",
"firstname": "<anystring>",
"lastname": "<anystring>",
"birthdate": "<anydate>",
"maxWorkHours": 3,
"username": "<anystring>",
"permissions": "<anystring>",
"lastUpdate": "<anydate>"
});
console.log(e);
Run Code Online (Sandbox Code Playgroud)
我有以下C#类:
public class JsonBackup
{
public int Added { set; get; }
public int DEVCount { set; get; }
public int DS1Count { set; get; }
public IList<ViewEvent> Events { get; set; }
public IEnumerable<string> Errors { set; get; }
public int Rejected { set; get; }
public bool Success { set; get; }
public int Updated { set; get; }
}
Run Code Online (Sandbox Code Playgroud)
这个代码将JSON数据返回给我的浏览器:
return Json(new JsonBackup
{
Added = added,
DEVCount = devCount,
DS1Count = ds1Count,
Events = t.Events,
Rejected …Run Code Online (Sandbox Code Playgroud) 我有这个简单的组件
import {Component} from 'angular2/core';
import {RouterLink, RouteParams} from 'angular2/router';
import {Http, Response, Headers} from 'angular2/http';
import {User} from '../../models/user';
import 'rxjs/add/operator/map';
@Component({
template: `
<h1>{{user.name}} {{user.surname}}</h1>
`,
directives: [RouterLink],
})
export class UserComponent {
user: User;
constructor(private routeParams: RouteParams,
public http: Http) {
this.user = new User();
this.http.get('http://localhost:3000/user/' + this.routeParams.get('id'))
.map((res: Response) => res.json())
.subscribe((user: User) => this.user = user);
console.log(this.user);
}
}
Run Code Online (Sandbox Code Playgroud)
为什么不subscribe将响应转换为完整User对象.当我记录user变量时,我的控制台说User {_id: undefined, name: undefined, surname: undefined, email: undefined} …
我试图了解如何使用Angular 2中的http.get和Observables将服务调用的结果映射到对象.
看看这个Plunk
在方法getPersonWithGetProperty中,我期望返回一个类型为PersonWithGetProperty的Observable.然而!我无法访问属性fullName.我想我必须创建PersonWithGetProperty类的新实例,并使用类构造函数将响应映射到这个新对象.但是你如何在方法getPersonWithGetProperty中做到这一点?
import {Injectable} from '@angular/core';
import {Http, Response} from '@angular/http';
import {Observable} from 'rxjs/Rx';
export class PersonWithGetProperty {
constructor(public firstName: string, public lastName: string){}
get fullName(): string {
return this.firstName + ' ' + this.lastName;
}
}
@Injectable()
export class PersonService {
constructor(private http: Http) {
}
getPersonWithGetProperty(): Observable<PersonWithGetProperty> {
return this.http.get('data/person.json')
.map((response: Response) => <PersonWithGetProperty>(response.json()));
}
}
Run Code Online (Sandbox Code Playgroud) 我想知道将get响应中的http响应映射到类而不是基本Javascript对象的最佳方法是什么.
在我目前的尝试中,我很简单new ClassName(data),但可能有一个模糊的Angular指定和完全令人敬畏的方式,我不知道.
这是我目前的代码:
getPost(id:number){
return this._http.get(this._postsUrl+'/'+id)
.map(res => new Post(res.json().data))
.do(data => console.log(data))
.catch(this.handleError);
}
Run Code Online (Sandbox Code Playgroud)
我需要Post成为一个类,而不仅仅是一个接口,因为我有内部方法.
我按照HeroTutorial和http"开发人员指南"进行操作,并按照他们的getHeroes方法执行:
getHeroes () {
return this.http.get(this._heroesUrl)
.map(res => <Hero[]> res.json().data)
.catch(this.handleError);
}
Run Code Online (Sandbox Code Playgroud)
我不知何故希望这<Hero[]>部分能做到这一点:拿Hero类并创建它的新实例,但我的测试表明它没有,这几乎只是Typescript知道会发生什么.
有任何想法吗 ?谢谢!
typescript ×7
angular ×5
json ×5
javascript ×3
http ×1
http-get ×1
node.js ×1
object ×1
observable ×1
parsing ×1
prototype ×1
rxjs ×1