71、salesforce的JSON方法

来源:互联网 发布:微博个性域名是什么 编辑:程序博客网 时间:2024/06/07 06:22
List<Merchandise__c> merchandise = [select Id,Name,Price__c,Quantity__c from Merchandise__c limit 1];String goodsToJson = JSON.serialize(merchandise);//通过serialize方法序列化成JSON内容String goodsToJsonPretty = JSON.serializePretty(merchandise);//通过serializePretty方法序列化成JSON内容,以精美的输出格式输出//接上面Serialize的Sample,用于将JSON内容反序列化成Apex的Object对象List<Merchandise__c> merchandise2 = (List<Merchandise__c>)JSON.deserialize(goodsToJson, List<Merchandise__c>.class);for(Merchandise__c item : merchandise2){    if(item.Name != null){        System.debug(item.Name);    }}//此方法用于将指定的JSON内容反序列化成基本数据类型的集合,如果不是基本数据类型,则在反序列化时报异常String jsonList = '[{"2":"object2","1":"object1"}]';List<Object> listJson = (List<Object>)JSON.deserializeUntyped(jsonList);for(Object listItem : listJson){    if(listItem instanceof Map<String,Object>){        System.debug('通过json 的反序列化(Map)' + (Map<String,Object>)listItem);    }else{        System.debug('通过json 的反序列化' + listItem);    }}//此类包含的方法用来通过标准的JSON编码将object对象序列化成JSON内容,方法主要作用为将各种类型的值写入//JSON content中JSONGenerator jsonGenerator = JSON.createGenerator(true);jsonGenerator.writeStartArray();jsonGenerator.writeStartObject();jsonGenerator.writeBooleanField('isStatus', true);jsonGenerator.writeEndObject();jsonGenerator.writeEndArray();jsonGenerator.close();System.debug(jsonGenerator.getAsString());//JSONParser 用来解析一个调用了外部服务器的JSON格式的返回的响应内容,例如WEB service callout的json格式String JSONContent = '{"firstName":"John"}';JSONParser parser = JSON.createParser(JSONContent);//Advance to the next tokenwhile(parser.nextToken()!=null){    System.debug('Current token: ' + parser.getCurrentToken());}String JSONContent1 = '{"isActive":true}';JSONParser parser1 = JSON.createParser(JSONContent1);//Advance to the start object markerparser1.nextToken();//Advance to the next valueparser1.nextValue();//Get the Boolean value.Boolean isAcive1 = parser1.getBooleanValue();System.debug(parser1.nextToken());System.debug(parser1.nextValue());System.debug(isAcive1);

 

原创粉丝点击