3

Is it possible to serialize this JSON to Form-data in Apex?

The JSON we received:

[{"vendorcode":"4444","startDate":"2014-03-02","client":[{"name":"John"}]}]

We need to serialize it to Form-Data, and the result will be this:

data[0][vendorCode]=4444&data[0][startDate]=2014-03-02&data[0][client][0][name]=John

Right now we have this code for a simple JSON without lists inside, like client in the example above, but the problem is how to used for more levels:

    List<Object> l = (List<Object>)JSON.deserializeUntyped(jsonInput);     

    String fields = ''; 
    Object val;
    Map<String, Object> m;
    for(Integer i=0; i< l.size();i++){
        m = (Map<String, Object>) l[i];

        for(String key: m.keySet()){  
            val = m.get(key)!= null ? m.get(key):'';
            fields += EncodingUtil.urlEncode('data['+String.valueOf(i)+']['+String.valueOf(key)+']', 'UTF-8'); 
            fields +='='+ EncodingUtil.urlEncode(String.valueOf(val), 'UTF-8')+'&';

        } 
    } 

    return fields;

We have this in jQuery, but i can´t find something like this in apex:

https://api.jquery.com/jQuery.param/

2
  • You want data in apex class ?Sorry i did not get your question.Welcome to this site and please provide more info to questions Commented Mar 11, 2014 at 16:05
  • Sorry, i tried to explain better
    – JCP
    Commented Mar 11, 2014 at 16:31

1 Answer 1

1

You'll need to pre-create the data structure in an apex class to deserialize into that.

There's a teriffic online app, created by metadaddy and superfell, that can generate the class for you from the JSON string: http://json2apex.herokuapp.com

In your case, it will generate this APEX:

public class Vendor {

public String vendorcode;
public String startDate;
public List<Client> client;

public class Client {
    public String name;
}


public static Vendor parse(String json) {
    return (Vendor) System.JSON.deserialize(json, Vendor.class);
}

static testMethod void testParse() {
    String json = '[{\"vendorcode\":\"4444\",\"startDate\":\"2014-03-02\",\"client\":[{\"name\":\"John\"}]}]';
    Vendor obj = parse(json);
    System.assert(obj != null);
}
}
1
  • That's one of my favorite apps; I use it all the time.
    – Mike Chale
    Commented Mar 12, 2014 at 15:19

You must log in to answer this question.

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