Fix toJsonClassLoaderContextRec size bug

toJsonClassLoaderContextRec's size is twice as large than expected. And
the initial values is filled with null value.

Bug: 158843648
Test: m nothing(testcase is added)
Change-Id: I24c23269bd16baa18481f34b85c543d41f26d0e0
diff --git a/dexpreopt/class_loader_context.go b/dexpreopt/class_loader_context.go
index ad52b00..f76a205 100644
--- a/dexpreopt/class_loader_context.go
+++ b/dexpreopt/class_loader_context.go
@@ -544,13 +544,13 @@
 // Recursive helper for toJsonClassLoaderContext.
 func toJsonClassLoaderContextRec(clcs []*ClassLoaderContext) []*jsonClassLoaderContext {
 	jClcs := make([]*jsonClassLoaderContext, len(clcs))
-	for _, clc := range clcs {
-		jClcs = append(jClcs, &jsonClassLoaderContext{
+	for i, clc := range clcs {
+		jClcs[i] = &jsonClassLoaderContext{
 			Name:        clc.Name,
 			Host:        clc.Host.String(),
 			Device:      clc.Device,
 			Subcontexts: toJsonClassLoaderContextRec(clc.Subcontexts),
-		})
+		}
 	}
 	return jClcs
 }
diff --git a/dexpreopt/class_loader_context_test.go b/dexpreopt/class_loader_context_test.go
index 86f7871..610a4c9 100644
--- a/dexpreopt/class_loader_context_test.go
+++ b/dexpreopt/class_loader_context_test.go
@@ -155,6 +155,29 @@
 	})
 }
 
+func TestCLCJson(t *testing.T) {
+	ctx := testContext()
+	m := make(ClassLoaderContextMap)
+	m.AddContext(ctx, 28, "a", buildPath(ctx, "a"), installPath(ctx, "a"), nil)
+	m.AddContext(ctx, 29, "b", buildPath(ctx, "b"), installPath(ctx, "b"), nil)
+	m.AddContext(ctx, 30, "c", buildPath(ctx, "c"), installPath(ctx, "c"), nil)
+	m.AddContext(ctx, AnySdkVersion, "d", buildPath(ctx, "d"), installPath(ctx, "d"), nil)
+	jsonCLC := toJsonClassLoaderContext(m)
+	restored := fromJsonClassLoaderContext(ctx, jsonCLC)
+	android.AssertIntEquals(t, "The size of the maps should be the same.", len(m), len(restored))
+	for k := range m {
+		a, _ := m[k]
+		b, ok := restored[k]
+		android.AssertBoolEquals(t, "The both maps should have the same keys.", ok, true)
+		android.AssertIntEquals(t, "The size of the elements should be the same.", len(a), len(b))
+		for i, elemA := range a {
+			before := fmt.Sprintf("%v", *elemA)
+			after := fmt.Sprintf("%v", *b[i])
+			android.AssertStringEquals(t, "The content should be the same.", before, after)
+		}
+	}
+}
+
 // Test that unknown library paths cause a validation error.
 func testCLCUnknownPath(t *testing.T, whichPath string) {
 	ctx := testContext()