22
33import okhttp3 .Request ;
44import okhttp3 .ResponseBody ;
5+
56import org .json .JSONArray ;
67import org .json .JSONException ;
78import org .json .JSONObject ;
9+
810import retrofit2 .Call ;
911import retrofit2 .Response ;
1012
2022import java .util .logging .Level ;
2123import java .util .logging .Logger ;
2224import java .util .stream .IntStream ;
25+ import com .fasterxml .jackson .databind .ObjectMapper ; // Jackson for JSON parsing
26+ import com .fasterxml .jackson .databind .json .JsonMapper ;
27+ import com .fasterxml .jackson .databind .node .ObjectNode ;
28+ import com .fasterxml .jackson .databind .type .MapType ;
2329
2430import static com .contentstack .sdk .Constants .*;
2531
@@ -186,6 +192,14 @@ public void send() {
186192 }
187193 }
188194
195+ private JSONObject createOrderedJSONObject (Map <String , Object > map ) {
196+ JSONObject json = new JSONObject ();
197+ for (Map .Entry <String , Object > entry : map .entrySet ()) {
198+ json .put (entry .getKey (), entry .getValue ());
199+ }
200+ return json ;
201+ }
202+
189203 private void getService (String requestUrl ) throws IOException {
190204
191205 this .headers .put (X_USER_AGENT_KEY , "contentstack-delivery-java/" + SDK_VERSION );
@@ -210,16 +224,22 @@ private void getService(String requestUrl) throws IOException {
210224 if (request != null ) {
211225 response = pluginResponseImp (request , response );
212226 }
213- String responseBody = response .body ().string ();
214227 try {
215- responseJSON = new JSONObject (responseBody );
228+ // Use Jackson to parse the JSON while preserving order
229+ ObjectMapper mapper = JsonMapper .builder ().build ();
230+ MapType type = mapper .getTypeFactory ().constructMapType (LinkedHashMap .class , String .class ,
231+ Object .class );
232+ Map <String , Object > responseMap = mapper .readValue (response .body ().string (), type );
233+
234+ // Use the custom method to create an ordered JSONObject
235+ responseJSON = createOrderedJSONObject (responseMap );
216236 if (this .config .livePreviewEntry != null && !this .config .livePreviewEntry .isEmpty ()) {
217237 handleJSONArray ();
218238 }
219239 connectionRequest .onRequestFinished (CSHttpConnection .this );
220240 } catch (JSONException e ) {
221241 // Handle non-JSON response
222- setError ("Invalid JSON response: " + responseBody );
242+ setError ("Invalid JSON response" );
223243 }
224244 } else {
225245 assert response .errorBody () != null ;
0 commit comments