0

I have the a JSON string which contains of User,Account and contact details. How do I deserialize the JSON using Apex.

Json input is given below:

[
    {
        \"us\":{
        \"attributes\":{
        \"type\":\"User\",
        \"url\":\"/services/data/v39.0/sobjects/User/00528000004fOcqAAE\"
        },
        \"Id\":\"00528000004fOcqAAE\",
        \"LastName\":\"Contact Last Name\",
        \"Username\":\"some1@gmail.com\",
        \"Email\":\"some@gmail.com\",
        \"ContactId\":\"0032800000g7iJjAAI\"
        },
        \"con\":
        {
        \"attributes\":{
        \"type\":\"Contact\",
        \"url\":\"/services/data/v39.0/sobjects/Contact/0032800000g7iJjAAI\"
        },
        \"Id\":\"0032800000g7iJjAAI\",
        \"AccountId\":\"0012800000z7RzkAAE\",
        \"LastName\":\"Contact Last Name\",
        \"Account\":{
        \"attributes\":{
        \"type\":\"Account\",
        \"url\":\"/services/data/v39.0/sobjects/Account/0012800000z7RzkAAE\"
        },
        \"Id\":\"0012800000z7RzkAAE\",
        \"Name\":\"Test Account Name sree\"
        }
        },
        \"acc\":{
        \"attributes\":{
        \"type\":\"Account\",
        \"url\":\"/services/data/v39.0/sobjects/Account/0012800000z7RzkAAE\"
        },
        \"Id\":\"0012800000z7RzkAAE\",
        \"Name\":\"Test Account Name sree\"
        }
    }
]

i am getting this json from the following class:

@RestResource(urlMapping='/threeobjects/*')
Global class ThreeObjects_Getting {

    @HttpGet
    global static String doGet(){

        List<MultiWrapper> listmw = new List<MultiWrapper>();

        RestRequest req = RestContext.request;
        RestResponse res = RestContext.response;

        Map<Id, User> contactToUser = new Map<Id, User>();
        for (User u : [select Id, FirstName, LastName, UserName, Email,ContactId from User where ContactId != null limit 1] ) {
            contactToUser.put(u.ContactId, u);
        }

        for (Contact c : [select Id, AccountId, Lastname, Firstname, Email, Account.Id, Account.Name, Account.Phone from Contact where Id in :contactToUser.keySet()]) {
            listmw.add(new MultiWrapper(contactToUser.get(c.Id), c.Account, c));
        }

        System.debug('mw::::'+listmw);
        return json.serialize(listmw);

    }
    Global class MultiWrapper {
       User us;
       Account acc;
       Contact con;

       Public MultiWrapper (User us, Account acc, Contact con){
           this.us = us;
           this.acc = acc;
           this.con = con;
       }
    }
    @HttpPut
    global static String doPut(){
        String jsonstring = doGet();
        System.debug('jsonstring::::'+jsonstring);

        JSONParser parser = JSON.createParser(jsonstring);
        while (parser.nextToken() != null) {
            if (parser.getCurrentToken() == JSONToken.START_ARRAY) {
                while (parser.nextToken() != null) {
                    if (parser.getCurrentToken() == JSONToken.START_OBJECT) {
                        Jsonparsercls le = (Jsonparsercls)parser.readValueAs(Jsonparsercls.class);
                        System.debug('leee::'+le);

         /*               List<Jsonparsercls> myList = (List<Jsonparsercls>)System.JSON.deserialize(jsonstring, List<String>.class);
                        System.debug('myList::'+myList);   */ 
                    }
                }
            }
        }
        return jsonstring;
    }
    public class Jsonparsercls{
        Account acc{get;set;}
        Contact con{get;set;}
        User use{get;set;}
    }
}

while I am trying with

List<Jsonparsercls> myList = (List<Jsonparsercls>)System.JSON.deserialize(jsonstring, List<Jsonparsercls>.class)

I am getting error like Illegal value for primitive

How can I read data from jsonstring?

  • 1
    The text you have posted isn't JSON, its JSON that has been escaped. So first get rid of that escaping if you control the source of the JSON. – Keith C Feb 14 '17 at 12:01
  • @Keith C. i am getting this JSON input from Get method in Rest api method. Where as rest api get method returning in the form Account, contact and User in Json format – user37550 Feb 14 '17 at 12:06
  • @Keith C, How can i get rid of JSON, Can you please explain how can i get it? – user37550 Feb 14 '17 at 12:24
  • See my answer on that (relevant only if the JSON is coming from Apex). – Keith C Feb 14 '17 at 12:38
1

On the point about how the JSON gets spurious escaping added this is a common cause in Apex:

@HttpGet
global static String doGet() {
    Contact[] contacts = ...;
    return JSON.serialize(contacts);
}

where the method signature tells the framework that you want a string converting to JSON not a complex object converted to JSON.

This can be corrected using either:

@HttpGet
global static Contact[] doGet() {
    Contact[] contacts = ...;
    return contacts;
}

or:

@HttpGet
global static void doGet() {
    Contact[] contacts = ...;
    RestResponse res = RestContext.response;
    if (res == null) {
        res = new RestResponse();
        RestContext.response = res;
    }
    res.statusCode = 200;
    res.responseBody = Blob.valueOf(JSON.serialize(contacts));
}

where the former is simpler but is very painful if you are working on a managed package because the signature can't be changed later.

  • Still i had a doubt on this.. Clearly i updated my question. Could you please go through it and please post your answer again – user37550 Feb 14 '17 at 13:19
  • @sree Your GET code follows the anti-pattern if show first in this answer; return the list directly and change the signature to global static List<MultiWrapper> doGet() and the platform will return valid JSON over the HTTP call. – Keith C Feb 14 '17 at 13:29
  • But we will get an error at list<Jsonparsercls> MultiWrapperList = (list<Jsonparsercls>)JSON.deserialize(jsonstring,list<Jsonparsercls>.class);? – user37550 Feb 14 '17 at 14:05
  • A reason might be that in one class you have User us; and the other User use{get;set;}. I suggest you use the same class for both the serialize and deserialize. – Keith C Feb 14 '17 at 14:08
0

There is nice online tool available http://json2apex.herokuapp.com/ where you just need to paste your JSON and in return it will give you an APEX by clicking on CREATE APEX button and using JSON.Deserialize you can get the output you want.

Refer this question this has detail information, it might help you How to deserialize a JSON String to Apex you will get an idea.

  • @NachiketDeshpande you should edit your answer to include the relevant parts of the link. – battery.cord Feb 15 '17 at 13:19
  • @battery.cord done edited my answer. – Nachiket Deshpande Feb 15 '17 at 14:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy