3

My Apex code talks to the OpenAI API which has a Message object.

This is the Apex Wrapper class for Message:

public class Message {
  public String id;
  public String role;
  public String run_id;
  public List<Content> content = new List<Content>();
  public Map<String, Object> metadata = new Map<String, Object>();
}

JSON.serialize and deserialize() fail because Apex JSON cannot cope with type Object.

Is there a workaround for that?

2
  • Are you going to be actually using that metadata? If not, why not simply leave it out of your Message class?
    – Derek F
    Commented Apr 24 at 13:47
  • 1
    Also, the API documentation is frustratingly vague on what the metadata map actually is. Given it says the values are a max of 512 characters, would not a Map<String, String> be appropriate?
    – Derek F
    Commented Apr 24 at 13:50

1 Answer 1

7

You are correct in saying that Apex is limited regarding the deserialize method, but serialization works just fine. I think the workaround is to use the deserializeUntyped method instead. You'll get a Map<String, Object> and can cast the types as needed (dynamically).

Taking your example (without the Content object):

public class Message {
  public String id;
  public String role;
  public String run_id;
  public Map<String, Object> metadata = new Map<String, Object>();
}

Message m = new Message();
m.id = '1234';
m.metadata = new Map<String, Object>{ 'hello' => 'world' };

String jso = JSON.serialize(m);

Map<String, Object> data = (Map<String, Object>) JSON.deserializeUntyped(jso);
System.debug(data);
// {id=null, metadata={hello=world}, role=null, run_id=null}

System.debug(data.get('id'));
// 1234

System.debug(data.get('metadata'));
// {hello=world}

Map<String, Object> md = (Map<String, Object>) data.get('metadata');
System.debug(md.get('hello'));
// world

// This one fails with a specific type:
//System.debug(JSON.deserialize(jso, Message.class));

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .